额~~~~

P1600 [NOIP2016 提高组] 天天爱跑步

25th_engineer @ 2016-12-16 19:23:38

#include<stdio.h>
#include<string.h>
#define fo(i,a,b) for(i=a;i<=b;i++)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define N 301000
int w[N],last[N*10],next[N*10],to[N*10],tot=0,n,m,dfn[N],fa[N],son[N],top[N],size[N],g[N+N+N],deep[N],ans[N];
int ls[N*10],nx[N*10],dt[N*10],to1=0,la[N*10],ne[N*10],da[N*10],to2=0,yl[N];
int ls2[N*10],nx2[N*10],dt2[N*10],to3=0,la2[N*10],ne2[N*10],da2[N*10],to4=0;
void putin(int x,int y)
{
    next[++tot]=last[x];last[x]=tot;to[tot]=y;
}
void put1(int x,int y)
{
    nx[++to1]=ls[x];ls[x]=to1;dt[to1]=y;
}
void put2(int x,int y)
{
    ne[++to2]=la[x];la[x]=to2;da[to2]=y;
}
void put3(int x,int y)
{
    nx2[++to3]=ls2[x];ls2[x]=to3;dt2[to3]=y;
}
void put4(int x,int y)
{
    ne2[++to4]=la2[x];la2[x]=to4;da2[to4]=y;
}
void dg1(int x)
{
    int i;
    size[x]=1;int mx=0;
    for(i=last[x];i;i=next[i])
    {
        if(size[to[i]]) continue;
        fa[to[i]]=x;deep[to[i]]=deep[x]+1;
        dg1(to[i]);size[x]+=size[to[i]];
        if(size[to[i]]>size[mx]) mx=to[i];
    }
    son[x]=mx;
}
void dg2(int x)
{
    int i;
    dfn[x]=++tot;yl[tot]=x;if(son[x]) top[son[x]]=top[x],dg2(son[x]);
    for(i=last[x];i;i=next[i])
    {
        if(dfn[to[i]]) continue;
        top[to[i]]=to[i];dg2(to[i]);
    }
}
int lca(int x,int y)
{
    int f1=top[x],f2=top[y];
    for(;f1!=f2;) if(deep[f1]>=deep[f2]) x=fa[f1],f1=top[x];else y=fa[f2],f2=top[y];
    if(deep[x]<deep[y]) return x;else return y;
}
void lct(int x,int y)
{
    int z=lca(x,y),bz=1;
    int jy1=deep[x],jy2=deep[z]-deep[x]+deep[z];
    int f1=top[x],f2=top[y];
    for(;f1!=f2;)
    {
        if(deep[f1]>=deep[f2]) put1(dfn[x],jy1),put2(dfn[f1],jy1),x=fa[f1];
        else put3(dfn[f2],jy2),put4(dfn[y],jy2),y=fa[f2];
        f1=top[x],f2=top[y];
    }
    if(deep[x]<deep[y]) put3(dfn[x],jy2),put4(dfn[y],jy2);
    else put1(dfn[x],jy1),put2(dfn[y],jy1);
}
int main()
{
    freopen("running.in","r",stdin);
    freopen("running.out","w",stdout);
    int i,j,k;
    scanf("%d%d",&n,&m);int x,y;
    fo(i,1,n-1)
    {
        scanf("%d%d",&x,&y);
        putin(x,y);putin(y,x);
    }
    fo(i,1,n) scanf("%d",&w[i]);
    tot=0;deep[1]=1;top[1]=1;dg1(1);dg2(1);
    fo(i,1,m)
    {
        int x,y;scanf("%d%d",&x,&y);
        lct(x,y);
    }
    fo(i,1,n)
    {
        for(k=ls2[i];k;k=nx2[k]) g[dt2[k]+N]++;
        ans[yl[i]]+=g[deep[yl[i]]-w[yl[i]]+N];
        for(k=la2[i];k;k=ne2[k]) g[da2[k]+N]--;
    }
    fd(i,n,1)
    {
        for(k=ls[i];k;k=nx[k]) g[dt[k]+N]++;
        ans[yl[i]]+=g[deep[yl[i]]+w[yl[i]]+N];
        for(k=la[i];k;k=ne[k]) g[da[k]+N]--;
    }
    fo(i,1,n) printf("%d ",ans[i]);
    return 0;
}

by __世界第一弱__ @ 2016-12-16 19:29:46

~~额~~


|