Niu Ke Practice 62 C- Niu Niu dyed color (tree dp)

Meaning of the question:
Given a tree, there is a restriction to dye the dots on the tree into white or black. The color of any two black dots must also be black. Find the number of dyeing schemes.
Solution:
Let dp[i] denote the number of schemes with at least one black dot in the subtree with i as the root node, and the empty set is dp[i]+1
1. If the point u is a black dot, then how the child nodes are colored Yes, dp[u]=∏(dp[v]+1)
2. If u is a white point, then the child node has at least one black point, dp[u]+=dp[v] The
final answer is ans=dp [1]+1;
Code:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int mod=1e9+7;
const int MAXN=1e6+5;
int head[MAXN];
int cnt=0;
ll dp[MAXN];
struct node
{
    
    
    int to;
    int next;
}e[MAXN<<1];
void add(int u,int v)
{
    
    
    e[cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int u,int f)
{
    
    
    ll sum1=1;
    ll sum2=0;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
    
    
        int v=e[i].to;
        if(v==f) continue;
        dfs(v,u);
        sum1=sum1*(dp[v]+1)%mod;
        sum2=(sum2+dp[v])%mod;
    }
    dp[u]=sum1;
    dp[u]=(dp[u]+sum2)%mod;
}
int main()
{
    
    
    int n;
    cin>>n;
    memset(head,-1,sizeof head);
    int u,v;
    for(int i=1;i<=n-1;i++)
    {
    
    
        cin>>u>>v;
        add(u,v);
        add(v,u);
    }
    dfs(1,-1);
    ll ans=(dp[1]+1)%mod;
    printf("%lld\n",ans);
}



Guess you like

Origin blog.csdn.net/weixin_45755679/article/details/109098230