蔚来杯“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}
s∈sonx∏
(
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
(s∈sonx∑dps,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
x∑c∈0,1∑dpx,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;
}
博客内容介绍了如何使用树形动态规划(DP)解决一道关于寻找特定条件的连通子图数量的问题。题目要求在给定的一棵树中,计算所有度数为1且颜色相同的节点构成的连通子图的数量。博主给出了详细的解题思路,包括状态转移方程和代码实现,并在最后进行了公式简化和代码展示。
168

被折叠的 条评论
为什么被折叠?



