# Codeforces Round #582 (Div. 3) G. Path Queries（树上分块）

## 题目链接

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>

const int mod = 998244353;
const int maxn = 1e6 + 5;
const int inf = 1e7;
const long long onf = 1e18;
#define me(a, b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI 3.14159265358979323846
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int n, m;
int q[maxn], root[maxn], sum[maxn];
ll ans[maxn];

struct node {
int u, v, val;

bool friend operator<(node a, node b) {
return a.val < b.val;
}
} a[maxn];

int Find(int x) {
if (x == root[x])
return x;
return root[x] = Find(root[x]);
}

void init() {
for (int i = 1; i <= n; i++) {
sum[i] = 1, root[i] = i;
}
}

int main() {
//freopen("1.in", "r", stdin);
scanf("%d%d", &n, &m);
init();
for (int i = 1; i < n; i++)
scanf("%d%d%d", &a[i].u, &a[i].v, &a[i].val);
sort(a + 1, a + n);
int End = 0;
for (int i = 1; i <= m; i++) {
scanf("%d", &q[i]);
End = max(End, q[i]);
}
for (int i = 1; i < n; i++) {
int x1 = Find(a[i].u);
int y1 = Find(a[i].v);
if (x1 != y1) {
ll temp = (ll) sum[x1] * sum[y1];
sum[y1] += sum[x1], sum[x1] = 0;///将两个连通块合并成一个
root[x1] = y1;
ans[a[i].val] += temp;
}
}
for (int i = 1; i <= End; i++)///这点很好理解，因为是求满足小于给定边权的点的对数。
ans[i] += ans[i - 1];
for (int i = 1; i <= m; i++)
printf("%lld ", ans[q[i]]);
return 0;
}

09-02 55

08-31 490

11-24 2317

09-05 106

05-09 1156

10-22 75

03-18 27

04-02 329

07-11 56

#### 树上分块模板

©️2020 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。