fnoiyhyang @ 2021-10-05 18:03:46
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=330000;
int fa[N][22],w[N],n,m,dep[N],h[N],num;
int a1[N],c1[N],c2[N],ans[N];
struct node{
int u,v,next;
}d[N*2];
vector<int> a2[N],a3[N],a4[N];
void add(int u,int v){
d[num].u=u;
d[num].v=v;
d[num].next=h[u];
h[u]=num++;
d[num].u=v;
d[num].v=u;
d[num].next=h[v];
h[v]=num++;
}
void dfs1(int u,int fath){
dep[u]=dep[fath]+1;
fa[u][0]=fath;
for(int i=1;i<=20;++i)
fa[u][i]=fa[fa[u][i-1]][i-1];
for(int i=h[u];i!=-1;i=d[i].next)
if(d[i].v!=fath)
dfs1(d[i].v,u);
}
int lca(int u,int v){
if(dep[u]<dep[v])
swap(u,v);
for(int i=20;i>=0;--i)
if(dep[fa[u][i]]>=dep[v])
u=fa[u][i];
if(u==v)return u;
for(int i=20;i>=0;--i)
if(fa[u][i]!=fa[v][i]){
u=fa[u][i];
v=fa[v][i];
}
return fa[u][0];
}
void dfs(int u,int fath){
int x1=c1[dep[u]+w[u]];
int x2=c2[w[u]-dep[u]+n];
for(int i=h[u];i!=-1;i=d[i].next)
if(d[i].v!=fath)
dfs(d[i].v,u);
c1[dep[u]]+=a1[u];
for(int i=0;i<a2[u].size();++i)
c1[a2[u][i]]--;
for(int i=0;i<a3[u].size();++i)
c2[a3[u][i]]++;
for(int i=0;i<a4[u].size();++i)
c2[a4[u][i]]--;
ans[u]+=c1[dep[u]+w[u]]-x1+c2[w[u]-dep[u]+n]-x2;
}
int main(){
// freopen("P1600_13.in","r",stdin);
// freopen("1.txt","w",stdout);
scanf("%d%d",&n,&m);
num=0;
memset(h,-1,sizeof h);
for(int i=1;i<n;++i){
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
}
dfs1(1,0);
for(int i=1;i<=n;++i)
scanf("%d",&w[i]);
memset(a1,0,sizeof a1);
for(int i=1;i<=m;++i){
int s,t;
scanf("%d%d",&s,&t);
int p=lca(s,t);
a1[s]++;
a2[fa[p][0]].push_back(dep[s]);
a3[t].push_back(dep[s]-2*dep[p]+n);
a4[p].push_back(dep[s]-2*dep[p]+n);
}
dfs(1,0);
for(int i=1;i<=n;++i)
printf("%d ",ans[i]);
return 0;
}
评测结果
by fnoiyhyang @ 2021-10-05 18:04:14
rt