반응형

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

 

16393번: Lost Map

The first line of input will contain the integer n (2 ≤ n ≤ 2 500), the number of villages in this region. The next n lines will contain n integers each. The jth integer of the ith line is the distance from village i to village j. All distances are gre

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 각 도시마다 거리를 입력받고 i < j 일 때만 vector에 거리, 시작 도시, 도착 도시를 push 해 줍니다.

 

2. vector를 거리가 짧은 순으로 정렬해줍니다.

 

3. for문을 통해 vector를 돌며 Union Find를 이용하여 i와 j의 부모가 다를 때 i와 j를 합쳐주며 ans에 i, j를 넣어줍니다.

 

4. 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
#include<iostream>
#include<algorithm>
#include<vector>
#include<tuple>
#define ti tuple<int,int,int>
 
using namespace std;
 
int N;
int vect[2501];
vector<pair<int,int>> 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"&N);
    for (int i = 1; i <= N; i++) {
        vect[i] = i;
    }
 
    vector<ti> pq;
 
    for (int i = 1; i <= N; i++) {
        for (int j = 1; j <= N; j++) {
            int dist;
            scanf("%d"&dist);
            if (i < j) {
                pq.emplace_back(dist, i, j);
            }
        }
    }
 
    sort(pq.begin(), pq.end());
 
    for (auto& next : pq) {
        int a = get<1>(next);
        int b = get<2>(next);
        if (Find(a) != Find(b)) {
            Union(a,b);
            ans.emplace_back(a, b);
        }
    }
 
    for (auto next : ans) {
            printf("%d %d\n", next.first, next.second);
    }
}
cs
반응형

+ Recent posts