[백준] 1922번 네트워크 연결 (C++)

2025. 9. 18. 19:49·Algorithm
728x90

https://www.acmicpc.net/problem/1922

 

 

이 문제는 N개의 컴퓨터 개수가 주어지고 M개의 컴퓨터와 연결된 선, 비용이 주어진다.

이때 최소한의 비용을 사용하여 모든 N개의 컴퓨터가 연결되어야 한다.

 

따라서 문제를 읽어보면 최소신장트리를 구현하는 문제인걸 바로 알아챌 수 있다.

 

 

정답코드

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
#define endl "\n"
#define MAX 1e9

struct coordinate {
    int x;
    int y;
    int r;
};

int dx[] = {-1, 1, 0, 0, 1, -1, -1, 1};
int dy[] = {0, 0, -1, 1, -1, 1, -1, 1};
int N, M;
int unf[1001];
vector<tuple<int, int, int>> v;

int Find(int a) {
    if(a == unf[a]) return a;
    return unf[a] = Find(unf[a]);
}

void Union(int a, int b) {
    a = Find(a);
    b = Find(b);

    if(a < b) unf[a] = b;
    else unf[b] = a;
}

bool isUnion(int a, int b) {
    a = Find(a);
    b = Find(b);

    if(a != b) return false;
    return true;
}

void solve() {
    sort(v.begin(), v.end());

    int answer = 0;

    for(auto it : v) {
        auto [cost, Node1, Node2] = it;

        if(!isUnion(Node1, Node2)) {
            answer += cost;
            Union(Node1, Node2);
        }
    }

    cout << answer;
}

void Init() {
    for(int i = 1; i <= N; i++) {
        unf[i] = i;
    }
}

void input() {
    cin >> N >> M;

    for(int i = 0; i < M; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        v.push_back({c, a, b});
    }

    Init();
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    input();
    solve();
}

 

solve함수를 살펴보자

void solve() {
    sort(v.begin(), v.end());

    int answer = 0;

    for(auto it : v) {
        auto [cost, Node1, Node2] = it;

        if(!isUnion(Node1, Node2)) {
            answer += cost;
            Union(Node1, Node2);
        }
    }

    cout << answer;
}

 

먼저 입력된 간선을 비용을 기준으로 오름차순으로 정렬한다.

 

이후 배열을 순회하면서 1번 노드와 2번노드가 연결이 되어 있으면 합치지 않고

연결되지 않았으면 합쳐서 비용을 따로 계산해 준다.

 

728x90
저작자표시 (새창열림)

'Algorithm' 카테고리의 다른 글

[백준] 13702번 이상한 술집 (C++)  (0) 2025.09.20
[백준] 12841번 정보대 등산 (C++)  (0) 2025.09.19
[백준] 9372번 상근이의 여행 (C++)  (0) 2025.09.17
[백준] 19638번 센티와 마법의 뿅망치 (C++)  (0) 2025.09.16
[백준] 2151번 거울 (C++)  (0) 2025.09.15
'Algorithm' 카테고리의 다른 글
  • [백준] 13702번 이상한 술집 (C++)
  • [백준] 12841번 정보대 등산 (C++)
  • [백준] 9372번 상근이의 여행 (C++)
  • [백준] 19638번 센티와 마법의 뿅망치 (C++)
쿨쿨.
쿨쿨.
  • 쿨쿨.
    All of the life
    쿨쿨.
  • 전체
    오늘
    어제
    • 분류 전체보기 (283) N
      • Programming (51) N
        • C, C++ (18)
        • Python (6)
        • Java (1)
        • HTML,CSS,JS (3)
        • SQL(DB) (13)
        • SpringBoot (7) N
        • Android (2)
        • CI,CD (1)
      • Algorithm (173)
        • Review (4)
      • Security (14)
        • WebHacking (3)
        • Websecurity (11)
      • OS (19)
        • Linux (12)
        • Mac os (2)
      • 머신러닝 (1)
      • CS(Computer Science) (12)
        • 컴퓨터 네트워크 (3)
        • 컴퓨터 구조 (1)
        • 인공지능 (8)
      • Docker (1)
      • Dev Book Review (3)
        • Clean Code (1)
        • Effective Java (0)
        • Real MySQL (2)
      • SWM (1)
      • Review (6)
      • AWS (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    wargame
    깊이우선탐색
    WebSecurity
    브루트포스
    다이나믹 프로그래밍
    트리
    그리디
    DFS
    BFS
    c언어
    Leviathan
    Bandit
    그래프 이론
    코딩
    에라토스테네스의 체
    우선순위 큐
    투포인터
    누적합
    시뮬레이션
    linux
    재귀
    구현
    정렬
    백준
    이분탐색
    우선순위큐
    다익스트라
    DP
    비트마스킹
    백트래킹
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.6
쿨쿨.
[백준] 1922번 네트워크 연결 (C++)
상단으로

티스토리툴바