반응형

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

 

1414번: 불우이웃돕기

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

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 모든 간선을 입력받아 arr 배열에 저장하고, ans에 모든 랜선의 길이를 더해줍니다.

 

2. arr 배열을 for문을 통해 돌면서 노드들을 이어주고, ans에서 그 길이를 빼줍니다.

 

3. 연결된 간선의 길이가 N-1개라면 ans를 출력하고, 그렇지 않다면 -1을 출력합니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<vector>
#include<algorithm>
 
using namespace std;
 
struct node {
    int a, b, c;
};
 
bool cmp(node left, node right)
{
    return left.c < right.c;
}
 
int N;
vector<node> arr;
int vect[51];
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++) {
        char temp[55];
        scanf("%s", temp);
        for (int j = 1; j <= N; j++) {
            if (temp[j - 1>= 'a' && temp[j - 1<= 'z') {
                arr.push_back({ i,j, temp[j - 1- 'a' + 1 });
                ans += temp[j - 1- 'a' + 1;
            }
            else if (temp[j - 1>= 'A' && temp[j - 1<= 'Z') {
                arr.push_back({ i,j,temp[j - 1- 'A' + 27 });
                ans += temp[j - 1- 'A' + 27;
            }
        }
 
        vect[i] = i;
    }
 
    sort(arr.begin(), arr.end(), cmp);
 
    int cnt = 0;
 
    for (auto& next : arr) {
        const int a = next.a;
        const int b = next.b;
        const int c = next.c;
 
        if (Find(a) != Find(b)) {
            Union(a, b);
            ans -= c;
            cnt++;
        }
    }
 
    if (cnt != N - 1) {
        printf("-1");
    }
    else {
        printf("%d", ans);
    }
}
cs
반응형

+ Recent posts