|
沙发
楼主 |
发表于 2018-6-9 21:18:56
|
只看该作者
- #include <algorithm>
- #include <cstdio>
- using namespace std;
- const int N=300005;
- int f[N][20],to[N*5],ne[N*5],fi[N],dep[N],fir[N],v[N*5],w[N],
- cnt1[N],cnt2[N],ans[N],f1[N*2],f2[N*2],tot=0,cnt=0,n,m;
- void add(int x,int y){
- to[++tot]=y;ne[tot]=fi[x];fi[x]=tot;
- }
- void ADD(int x,int y,int z){
- to[++tot]=y;v[tot]=z;ne[tot]=fir[x];fir[x]=tot;
- }
- void dfs(int x){
- dep[x]=dep[f[x][0]]+1;
- for (int i=f[x][0],j=0;f[i][j];i=f[i][j++]) f[x][j+1]=f[i][j];
- for (int i=fi[x];i;i=ne[i])
- if (to[i]!=f[x][0]) f[to[i]][0]=x,dfs(to[i]);
- }
- int lca(int x,int y){
- if (dep[x]<dep[y]) std::swap(x,y);
- for (int i=18;dep[x]>dep[y];x=f[x][i])
- for (;i && dep[f[x][i]]<dep[y];i--);
- for (int i=18;x!=y;x=f[x][i],y=f[y][i])
- for (;i && f[x][i]==f[y][i];i--);
- return x;
- }
- void insert(int x){
- for (int i=fir[x];i;i=ne[i])
- if (!v[i]){
- cnt1[f1[to[i]-dep[x]+N]]--;
- cnt2[f2[to[i]+dep[x]]]--;
- }
- else if (v[i]==1) cnt2[f2[to[i]]]++;
- else cnt1[f1[to[i]+N]]++;
- }
- void dfs2(int x){
- int d1=w[x]-dep[x]+N,d2=w[x]+dep[x],y=f1[d1],z=f2[d2];
- f1[d1]=f2[d2]=x;
- for (int i=fi[x];i;i=ne[i])
- if (to[i]!=f[x][0]) dfs2(to[i]);
- insert(x);
- ans[x]+=cnt1[x]+cnt2[x];
- cnt1[y]+=cnt1[x];cnt2[z]+=cnt2[x];
- f1[d1]=y;f2[d2]=z;
- }
- int main(){
- scanf("%d%d\n",&n,&m);
- for (int i=1;i<n;i++){
- int x,y;
- scanf("%d%d\n",&x,&y);
- add(x,y);add(y,x);
- }
- dfs(1);
- for (int i=1;i<=n;i++) scanf("%d",&w[i]);
- for (int i=1;i<=m;i++){
- int x,y,z;
- scanf("%d%d\n",&x,&y);
- z=lca(x,y);
- if (dep[x]-dep[z]==w[z]) ans[z]++;
- ADD(z,dep[x]-dep[z],0);
- ADD(x,dep[x],1);
- ADD(y,dep[x]-dep[z]*2,-1);
- }
- dfs2(1);
- for (int i=1;i<=n;i++) printf("%d ",ans[i]);
- return 0;
- }
复制代码 |
|