一個有向圖,每條邊都有一個權值,有m個詢問,每個詢問找出有多少對點使得這些點對之間的最大邊權不大於q
直接建圖搞不好做,也許是我不會吧
考慮要查詢的值爲x,當前有一條邊,其權值爲x-1,連接的兩個連通分量大小爲sz1和sz2,那麼很顯然這條邊的貢獻就是sz1*sz2
而權值小的邊一直都對更大的查詢有貢獻。
從而想到,可以講邊和查詢排序,然後用並查集維護連通分量的大小。
#include<bits/stdc++.h>
using namespace std;
#define f first
#define s second
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
const int N = 2e5 + 10;
int fa[N],sz[N],n,m,a,b,c;
struct query{
int val,id;
LL ans;
}q[N];
struct edge{
int u,v,w;
}E[N];
int cmp1(const query & x, const query & y){
return x.val < y.val;
}
int cmp2(const query & x, const query & y){
return x.id < y.id;
}
int cmp3(const edge & x, const edge & y){
return x.w < y.w;
}
int find(int x){
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void Union(int u,int v){
u = find(u);
v = find(v);
fa[v] = u;
sz[u] += sz[v];
sz[v] = sz[u];
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
cin>>n>>m;
for(int i = 1 ; i <= n ; i++) fa[i] = i, sz[i] = 1;
for(int i = 0 ; i < n - 1; i ++) {
cin>>E[i].u>>E[i].v>>E[i].w;
}
sort(E,E+n-1,cmp3);
for(int i = 0 ; i < m; i ++) {
cin>>q[i].val;
q[i].id = i;
}
sort(q,q+m,cmp1);
int i = 0, j = 0;
LL res = 0 ;
q[0].ans = 0 ;
while(j < m){
if(j) q[j].ans = q[j-1].ans;
while(E[i].w <= q[j].val && i < n - 1 ){
int u = E[i].u , v = E[i].v;
q[j].ans += (LL)sz[find(u)] * sz[find(v)];
Union(u,v);
i++;
}
j++;
}
sort(q,q+m,cmp2);
for(int i = 0 ; i < m ;i ++) cout<<q[i].ans<<' ';cout<<endl;
return 0;
}