forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoneymatters.cpp
65 lines (52 loc) · 1.25 KB
/
moneymatters.cpp
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
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
// Find parent in disjoint set
ll find(vector<ll>& disjoint, ll a) {
if(disjoint[a] == -1) {
return a;
}
ll tmp = find(disjoint, disjoint[a]);
disjoint[a] = tmp;
return tmp;
}
// Join two people in disjoint set
void join(vector<ll>& disjoint, ll a, ll b) {
a = find(disjoint, a);
b = find(disjoint, b);
if(a == b) {
return;
}
disjoint[b] = a;
}
int main() {
ll people, friendships;
cin >> people >> friendships;
// Allocate memory
vector<ll> disjoint(people, -1);
vector<ll> debts(people, 0);
vector<ll> grouptotal(people, 0);
// Read in all debts
for(ll i = 0; i < people; i++) {
cin >> debts[i];
}
// Read in all friendships
ll f1, f2;
for(ll i = 0; i < friendships; i++) {
cin >> f1 >> f2;
join(disjoint, f1, f2);
}
// Calculate all group debts
for(ll i = 0; i < people; i++) {
grouptotal[find(disjoint, i)] += debts[i];
}
// Check if there's a nonzero group debt
for(auto i : grouptotal) {
if(i != 0) {
cout << "IMPOSSIBLE" << endl;
return 0;
}
}
cout << "POSSIBLE" << endl;
}