题面:定义一个树的value为树的所有联通子图的节点数之和
求给出的一个树的value
感觉很巧妙的一个树dp
因为是一个无根树,不妨把0号节点提起来作为根,记Tx为以x为根节点的子树
定义
定义Cx为在Tx中选择x的联通子图的个数
考虑两个树,分别以
那么,将
先考虑简单的,Croot的值,如果不选x,那么方案数不变,如果选
对于Sroot的值,同样考虑是否选择x,如果不选择,那么对
如果选择了x,情况稍微复杂一点,分别考虑
对于Tst上的点的贡献
每一个值为Sst的方案都对应着Cx次贡献,所以对Sroot的贡献为 Cx×Sst
对于Tx上的点
同样的,每一个值为Sx一个方案都对应着Cst次贡献,所以对Sroot的贡献为Cst×Sc
所以,Sroot=Sst+Cx×Sst+Cst×Sc=(1+Cx)×Sst+Cst×Sc
#include <bits/stdc++.h>
typedef long long LL;
using namespace std;
const int mod = 1000000007;
const int maxn = 112345;
LL dp[maxn][2];
vector<int> edge[maxn];
void Link(int st,int ed){
edge[st].push_back(ed);
edge[ed].push_back(st);
}
void init(int n){
for(int i=0;i<n;i++){
edge[i].clear();
}
}
void dfs(int st,int fa){
dp[st][1] = 1;
dp[st][0] = 1;
for(auto & x:edge[st]){
if(x != fa){
dfs(x,st);
(dp[st][1] *= dp[x][0] + 1) %= mod;
(dp[st][1] += dp[st][0] * dp[x][1]) %= mod;
(dp[st][0] *= dp[x][0] + 1) %= mod;
}
}
}
class SubtreesCounting {
public:
int sumOfSizes( int n, LL a0, LL b, LL c, LL m ) {
init(n);
for(int i=1;i<n;i++){
Link(i,a0 % i);
a0 = (b * a0 + c) % m;
}
dfs(0,-1);
LL ans = 0;
for(int i=0;i<n;i++){
(ans += dp[i][1]) %= mod;
}
return (int)ans;
}
};