[bzoj3522][Poi2014]Hotel【树形dp】

【题目链接】
  https://www.lydsy.com/JudgeOnline/problem.php?id=3522
【题解】
  有一种简单的方法是枚举中点然后统计答案。
  时间复杂度O(N2)
  但此题还有更巧妙的O(N)做法,见:
  https://blog.csdn.net/D_Vanisher/article/details/80040659

# include <bits/stdc++.h>
# define    N       1000100
# define    ll      long long
using namespace std;
int read(){
    int tmp=0, fh=1; char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') fh=-1; ch=getchar();}
    while (ch>='0'&&ch<='9'){tmp=tmp*10+ch-'0'; ch=getchar();}
    return tmp*fh;
}
struct Edge{
    int data,next;
}e[N*2];
int dep[N],per[N],head[N],place,n;
ll space[N*10];
ll *f[N],*g[N],ans,*now=space+N;
void build(int u, int v){
    e[++place].data=v; e[place].next=head[u]; head[u]=place;
}
void create(int id){
    f[id]=now; now=now+dep[id]*2+1; 
    g[id]=now; now=now+dep[id]*2+1;
}
void dep_cnt(int x, int fa){
    for (int ed=head[x]; ed!=0; ed=e[ed].next)
        if (e[ed].data!=fa){
            dep_cnt(e[ed].data,x);
            if (dep[e[ed].data]>dep[per[x]])
                per[x]=e[ed].data;
        }
    dep[x]=dep[per[x]]+1;
}
void solve(int x, int fa){
    f[x][0]=1;
    if (per[x]!=0){
        f[per[x]]=f[x]+1;
        g[per[x]]=g[x]-1;
        solve(per[x],x);
        ans=ans+g[per[x]][1];
    }
    for (int ed=head[x]; ed!=0; ed=e[ed].next)
        if (e[ed].data!=fa&&e[ed].data!=per[x]){
            create(e[ed].data);
            solve(e[ed].data,x);
            int y=e[ed].data;
            for(int j=dep[y];j>=0;j--){
                if(j) ans+=f[x][j-1]*g[y][j];
                ans+=g[x][j+1]*f[y][j];
                g[x][j+1]+=f[x][j+1]*f[y][j];
            }
            for(int j=0;j<=dep[y];j++){
                if(j)   g[x][j-1]+=g[y][j];
                f[x][j+1]+=f[y][j];
            }
        }
}
int main(){
    n=read();
    for (int i=1; i<n; i++){
        int u=read(), v=read();
        build(u,v); build(v,u);
    }
    dep_cnt(1,0);
    create(1);
    solve(1,0);
    printf("%lld\n",ans);
    return 0;
}

posted @ 2018-04-22 17:19  Vanisher  阅读(120)  评论(0编辑  收藏  举报