蔚来杯“2022牛客暑期多校训练营5 D:Birds in the tree

蔚来杯“2022牛客暑期多校训练营5 D:Birds in the tree

原题:https://ac.nowcoder.com/acm/contest/33190/D

题面

One day, when NIO was walking under the tree, he found that there are birds standing on the tree, and each bird is standing on one leaf. He wondered about in how many sub-trees form by connected vertex-induced subgraphs from the original tree, all birds are in the same gender. The number would be very large, just mod 1 0 9 + 7 10^9+7 109+7 in the output.

大意

给定一个有 n n n个节点的树,每个节点有一个颜色,分别有 0 0 0 1 1 1。求这颗树里有多少连通的子图,其中度数为 1 1 1的节点的颜色相同。注意取模

题解

用树形 d p dp dp,设 d p x , c dp_x,_c dpx,c ,表示以 x x x为根的子树内 x x x被选择,除 x x x外叶节点颜色为 c c c的方案数。
则其方案数为从 d p s o n , c dp\scriptstyle son,c dpson,c 中从0开始取,从而得到方案数可表示为:
d p x , c dp\scriptstyle x,c dpx,c = = = ∏ s ∈ s o n x \displaystyle\prod_{s \in son_x} ssonx ( 1 + d p s , c ) (1+dp\scriptstyle s,c) (1+dps,c)

x x x的颜色为 c o l x col_x colx,最终答案先加上以 x x x为叶节点的方案数,加上只有 x x x的图,再加上不以 x x x为叶节点的方案,去掉其中与子节点重复的方案与只有 x x x的图。
所以,得到
a n s = ans= ans= ∑ x \displaystyle\sum_{x} x ( ∑ s ∈ s o n x d p s , c o l x (\displaystyle\sum_{s \in son_x} dp\scriptstyle s,col_x (ssonxdps,colx + 1 ) +1) +1) + ∑ x ∑ c ∈ 0 , 1 d p x , c \displaystyle\sum_{x}\displaystyle\sum_{c \in {0,1}} dp\scriptstyle x,c xc0,1dpx,c − - ( c o l x = = c ) (col_x==c) (colx==c)

接着可以整理一下公式,写出代码

参考代码

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=3*1e5+5;
int dp[maxn],ans=0;
ll mod=1e9+7;
string s;
vector<int> e[maxn];
void dfs(int u,int fa,char c){
    ll mul=1;
    ll sum=0;
    for(auto i:e[u]){
        if(i==fa) continue;
        dfs(i,u,c);
        sum=(sum+dp[i])%mod;
        mul=mul*(dp[i]+1)%mod;
    }
    dp[u]=(mul-(s[u]!=c)+mod)%mod;
    if(s[u]==c) ans=(ans+dp[u])%mod;
    else ans=(ans+dp[u]-sum+mod)%mod;
}
int main()
{
    int n,x,y;
    while(cin>>n)
    {
        ans=0;
        cin>>s;
        for(int i=1;i<=n-1;i++)
        {
            cin>>x>>y;
            x--;
            y--;
            e[x].push_back(y);        
            e[y].push_back(x);
        }
        dfs(1,-1,'0');
        dfs(1,-1,'1');
        cout<<ans;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值