반응형
문제
https://www.acmicpc.net/problem/3830
접근방법
1) 접근 사고
2) 시간 복잡도
3) 배운 점
4) PS
정답 코드
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
|
#include<bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define pii pair<int,int>
#define mp(X,Y) make_pair(X,Y)
#define mt(X,Y) make_tuple(X,Y)
#define mtt(X,Y,Z) make_tuple(X,Y,Z)
#define ll long long
#define sz(v) (int)(v).size()
using namespace std;
const int MAX = 100001;
int n, m;
int parent[MAX];
ll dist[MAX];
int find(int c)
{
if(parent[c] == c)
return c;
int idx = find(parent[c]);
//현재 트리 형식으로 이루어져있으니 find를 통해 차이 값 들을 갱신 시켜주는 작업
dist[c] += dist[parent[c]];
return parent[c] = idx;
}
void merge(int a, int b, int diff)
{
int pa = find(a);
int pb = find(b);
if(pa == pb)
return;
//차이값 계산
dist[pb] = dist[a] - dist[b] + diff;
parent[pb] = pa;
return;
}
int main(void)
{
fastio;
while(1)
{
cin >> n >> m;
if(n == 0 && m == 0)
break;
for(int i = 1; i <= n; i++)
parent[i] = i;
fill(dist, dist + MAX, 0);
for(int i = 0; i < m; i++)
{
char cmd;
cin >> cmd;
if(cmd == '!')
{
int a, b, c;
cin >> a >> b >> c;
merge(a, b, c);
}
else if(cmd == '?')
{
int a, b;
cin >> a >> b;
if(find(a) != find(b))
cout << "UNKNOWN" <<"\n";
else
cout << dist[b] - dist[a] << "\n";
}
}
}
}
|
cs |
반응형