그래프/최소 신장 트리

불우이웃돕기

4gats 2024. 1. 11. 15:48

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

 

1414번: 불우이웃돕기

첫째 줄에 컴퓨터의 개수 N이 주어진다. 둘째 줄부터 랜선의 길이가 주어진다. i번째 줄의 j번째 문자가 0인 경우는 컴퓨터 i와 컴퓨터 j를 연결하는 랜선이 없음을 의미한다. 그 외의 경우는 랜선

www.acmicpc.net

 

기부할 수 있는 랜선의 길이의 최대값 =

모두 연결 된 랜선의 최솟값

"최소 신장 트리"로 만들면 되겠다.

 

문자열 받기

cin.get()

cin은 공백이나 개행이 나오면 입력 종료로 간주

cin.get()은 공백과 개행도 입력으로 간주

 

 

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
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <vector>
#include <queue>
 
using namespace std;
 
typedef struct Edge {
    int s, e, v;
    bool operator > (const Edge& temp) const {
        return v > temp.v;
    }
} Edge;
 
vector<int> parent;
 
int find(int a)
{
    if (a == parent[a])
        return a;
    else
        return parent[a] = find(parent[a]);
}
 
void munion(int a, int b)
{
    a = find(a);
    b = find(b);
 
    if (a != b)
        parent[b] = a;
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    int n;
    int sum = 0;
    cin >> n;
 
    priority_queue<Edge, vector<Edge>, greater<Edge>> pq;
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            char tmpc = cin.get();
 
            if (tmpc == '\n')
                tmpc = cin.get();
 
            int tmp = 0;
 
            if (tmpc >= 'a' && tmpc <= 'z')
                tmp = tmpc - 'a' + 1;
            else if (tmpc >= 'A' && tmpc <= 'Z')
                tmp = tmpc - 'A' + 27;
 
            sum += tmp;
 
            if (i != j && tmp != 0)
                pq.push(Edge{ i,j,tmp });
        }
    }
 
    parent.resize(n);
 
    for (int i = 0; i < n; i++)
        parent[i] = i;
 
    int used = 0;
    int result = 0;
 
    while (!pq.empty())
    {
        Edge now = pq.top();
        pq.pop();
 
        // 같은 부모가 아니라면
        // 연결해도 사이클이 생기지 않음
        if (find(now.s) != find(now.e))
        {
            munion(now.s, now.e);
            result += now.v;
            used++;
        }
    }
 
    if (used == n - 1)
        cout << sum - result << '\n';
    else
        cout << -1 << '\n';
}
cs