반응형

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

 

2406번: 안정적인 네트워크

첫째 줄에 두 정수 n(1 ≤ n ≤ 1,000), m(0 ≤ m ≤ 10,000)이 주어진다. n은 컴퓨터의 개수이며, m은 연결되어 있는 지사 컴퓨터들의 쌍의 개수이다. 다음 m개의 줄에는 두 정수 x, y가 주어진다. 이는 서

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. node struct를 만들어서 arr 배열에 u, v, c를 각각 저장합니다.

 

2. arr 배열을 c를 기준으로 오름차순으로 정렬합니다.

 

3. 1번 노드를 제외한 나머지 노드들을 mst로 이어주어야 하므로 arr 배열을 만들 때 1번 노드를 제외하고 넣어줍니다.

 

4. Union-Find를 이용하여 노드들을 연결시켜 주고, 이때 cost에 c를 더해주고, ans 배열에 각각의 노드를 push 해줍니다.

 

5. cost와 ans.size()를 출력하고, ans 배열에 있는 노드들을 출력해 줍니다.

 

[ 소스코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<iostream>
#include<vector>
#include<algorithm>
 
using namespace std;
 
struct node {
    int u;
    int v;
    int c;
};
 
bool cmp(node left, node right)
{
    return left.c < right.c;
}
 
int n, m;
int vect[1001];
vector<node> arr;
vector<pair<intint>> ans;
 
int Find(int num)
{
    if (vect[num] == num) return num;
    return vect[num] = Find(vect[num]);
}
 
void Union(int a, int b)
{
    int pa = Find(a);
    int pb = Find(b);
 
    vect[pb] = pa;
}
 
int main()
{
    scanf("%d %d"&n, &m);
 
    for (int i = 1; i <= n; i++) {
        vect[i] = i;
    }
 
    for (int i = 0; i < m; i++) {
        int x, y;
        scanf("%d %d"&x, &y);
        Union(x, y);
    }
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            int cost;
            scanf("%d"&cost);
            if (i < j && i != 1) {
                arr.push_back({ i,j,cost });
            }
        }
    }
 
    sort(arr.begin(), arr.end(), cmp);
 
    int cost = 0;
 
    for (auto& next : arr) {
        const int u = next.u;
        const int v = next.v;
        const int c = next.c;
 
        if (Find(u) != Find(v)) {
            Union(u, v);
            cost += c;
            ans.push_back({ u, v });
        }
    }
 
    printf("%d %d\n", cost, (int)ans.size());
 
    for (auto& next : ans) {
        printf("%d %d\n", next.first, next.second);
    }
}
cs
반응형

+ Recent posts