P2796 Facer的程序

P2796 Facer的程序     

树形dp    

其实就是求大树中小树的个数     

f[i]表示以i为根的答案    

f[i]=∏j∈i的孩子(f[j]+1)         

代码:    

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
typedef long long ll;
ll mod=1000000007ll;
ll f[N]={0};
ll ans=0;
int hed[N<<1],tal[N<<1],nxt[N<<1],cnt=0;
int n;
inline void addege(int x,int y){
    cnt++;
    tal[cnt]=y;
    nxt[cnt]=hed[x];
    hed[x]=cnt;
}
void dfs(int u,int fa){
    f[u]=1ll;
    for(int i=hed[u];i;i=nxt[i]){
        int v=tal[i];
        if(v==fa) continue;
        dfs(v,u);
        f[u]=f[u]*(f[v]+1ll);
        f[u]%=mod;
    }
    ans+=f[u]%mod;
    ans%=mod;
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<n;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        addege(x,y);
        addege(y,x); 
    }
    dfs(1,1);
    printf("%lld\n",ans);
    return 0;
} 

 

posted @ 2019-08-28 14:05  QYJ060604  阅读(91)  评论(0编辑  收藏  举报