C 牛牛染颜色 树形DP
链接:https://ac.nowcoder.com/acm/contest/5205/C
思路:
代码如下:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const ll maxn=1e6+10; 5 const ll mod=1e9+7; 6 ll dp[maxn][3]; 7 struct node 8 { 9 ll nxt; 10 ll v; 11 }G[maxn<<1]; ll head[maxn]; ll num; 12 void add(ll u,ll v) 13 { 14 G[++num].v=v;G[num].nxt=head[u];head[u]=num; 15 } 16 void dfs(ll u,ll fa) 17 { 18 dp[u][0]=1; 19 dp[u][1]=1; 20 for(ll i=head[u];i;i=G[i].nxt){ 21 ll v=G[i].v; 22 if(v==fa) continue; 23 dfs(v,u); 24 dp[u][1]=dp[u][1]*(dp[v][0]+dp[v][1])%mod; 25 dp[u][0]=dp[u][0]+(dp[v][0]+dp[v][1]-1)%mod; 26 dp[u][0]%=mod; 27 } 28 } 29 int main() 30 { 31 ll n; 32 scanf("%lld",&n); 33 for(ll i=1;i<n;i++){ 34 ll u,v; 35 scanf("%lld%lld",&u,&v); 36 add(u,v); 37 add(v,u); 38 } 39 dfs(1,0); 40 printf("%lld\n",(dp[1][0]+dp[1][1])%mod); 41 return 0; 42 }