-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhierarchy.cpp
More file actions
81 lines (61 loc) · 1.4 KB
/
hierarchy.cpp
File metadata and controls
81 lines (61 loc) · 1.4 KB
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
#include <iostream>
#include <vector>
using namespace std;
int n = 1000;
vector<int> set(n);
int find (int node) {
int curr = set[node];
if (curr == node) {
return curr;
} else {
set[node] = find(curr);
return set[node];
}
}
int main ()
{
cin >> n;
int qualifications[n];
for (int i = 0; i < n; i++) cin >> qualifications[i];
int m;
cin >> m;
vector<pair<int, pair<int, int>>> prs (n);
vector<int> heads (n, -1);
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
x--;
y--;
prs.push_back(make_pair(z, make_pair(x, y)));
heads[y] = x;
}
sort(prs.begin(), prs.end());
int received[n];
for (int i = 0; i < n; i++) {
set[i] = i;
received[i] = 0;
}
int tot = 0;
for (pair<int, pair<int, int>> p: prs) {
int set1 = find(p.second.first);
int set2 = find(p.second.second);
if (set1 != set2) {
if (!received[p.second.second]) {
tot += p.first;
set[set2] = set1;
received[p.second.second] = 1;
}
}
}
int totl = 0;
for (int i = 0; i < n; i++) {
if (heads[i] == -1) {
totl++;
if (totl > 1) {
tot = -1;
break;
}
}
}
cout << tot << "\n";
}