-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathG_Path_Queries.cpp
More file actions
77 lines (66 loc) · 1.66 KB
/
G_Path_Queries.cpp
File metadata and controls
77 lines (66 loc) · 1.66 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
#include <bits/stdc++.h>
using namespace std;
class DSU {
public:
vector<int> par, sz;
DSU(int n){
par.resize(n + 1);
iota(par.begin(), par.end(), 0);
sz.resize(n + 1, 1);
}
int find(int x){
return x == par[x] ? x : par[x] = find(par[x]);
}
bool merge(int u, int v) {
int p1 = find(u), p2 = find(v);
if (p1 == p2) return 0;
if (sz[p1] < sz[p2]) swap(p1, p2);
par[p2] = p1;
sz[p1] += sz[p2];
return 1;
}
};
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, q;
cin >> n >> q;
vector<array<int, 3>> edges;
for(int i=0;i<n-1;i++) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back({u, v, w});
}
sort(edges.begin(), edges.end(), [&](const array<int, 3> &a, const array<int, 3> &b){
return a[2] < b[2];
});
vector<pair<int, int>> qry;
for(int i=0;i<q;i++) {
int w;
cin >> w;
qry.push_back({w, i});
}
sort(qry.begin(), qry.end());
DSU ds(n + 1);
int j = 0;
vector<long long> ans(q);
long long cnt = 0;
for(int i=0;i<q;i++) {
int limit = qry[i].first;
int id = qry[i].second;
while(j < n - 1 && edges[j][2] <= limit) {
int u = edges[j][0], v = edges[j][1];
int t1 = ds.find(u);
int t2 = ds.find(v);
if(t1 != t2) {
cnt += 1LL * ds.sz[t1] * ds.sz[t2];
ds.merge(u, v);
}
j++;
}
ans[id] = cnt;
}
for(int i=0;i<q;i++) cout << ans[i] << " ";
return 0;
}