# Codeforces 1213G Path Queries

cf题面

## 源代码

#include<cstdio>
#include<algorithm>

const int MAXN=2e5+5;
int n,m;

struct Que{
int id,w;
long long ans;
}q[MAXN];
bool cmp1(Que & a,Que & b){return a.w<b.w;}
bool cmp2(Que & a,Que & b){return a.id<b.id;}
struct Edge{
int u,v,w;
bool operator < (const Edge & x)const{
return w<x.w;
}
}e[MAXN];

int fa[MAXN],sz[MAXN];
int find(int x)
{
return fa[x]=fa[x]==x?x:find(fa[x]);
}
void uni(int x,int y)
{
x=find(x);
y=find(y);
fa[x]=y;
sz[x]+=sz[y];
sz[y]=sz[x];
}

int main()
{
//  freopen("test.in","r",stdin);
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
}
for(int i=0;i<m;i++)
{
scanf("%d",&q[i].w);
q[i].id=i;
q[i].ans=0;
}
std::sort(e+1,e+n);
std::sort(q,q+m,cmp1);
for(int i=1;i<=n;i++) fa[i]=i,sz[i]=1;
for(int i=0,pos=1;i<m;i++)
{
q[i].ans=q[i-1].ans;
while(pos<n&&e[pos].w<=q[i].w)
{
int u=e[pos].u,v=e[pos].v;
q[i].ans+=1LL*sz[find(u)]*sz[find(v)];
uni(u,v);
pos++;
}
}
std::sort(q,q+m,cmp2);
for(int i=0;i<m;i++) printf("%lld ",q[i].ans);
return 0;
}
posted @ 2019-09-05 15:09  wawcac  阅读(...)  评论(...编辑  收藏