D. Sasha and a Walk in the City
题意
树中任意一条路径上黑色点的数量不超过两个,请问存在多少种树
分析
先随便找一个节点作为根节点,然后分类讨论
假如根到叶子节点的路径上有两个黑色节点,则不能再添加其他点了
如果根到叶子节点的路径上有一个黑色节点,则可以还可以在不在这条路径上的地方放黑色节点
在弄清楚规则后,就可以用dp了(真是万能啊,完全没有要用dp的intuition)
其实dp只能算一种主动运用的方法,当后者于前者有继承关系时,就可以用了,状态的设计也是很巧妙
code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod=998244353;
int dp[300005][3]={0};
vector<int> G[300005];
void dfs(int now,int fa)
{
    dp[now][0]=1;
    dp[now][2]=0;
    int tem=1;
    for(auto next:G[now])
    {
        if(next==fa) continue;
        dfs(next,now);
        tem*=(1+dp[next][1]);
        dp[now][2]+=dp[next][2]+dp[next][1];
    }
    dp[now][1]=tem;
}
void solve()
{
    int n;
    cin>>n;
    for(int i=1;i<n;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    dfs(1,1);
    cout<<dp[1][1]+dp[1][2]+1<<'\n';
    for(int i=1;i<=n;i++) G[i].clear();
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    cin>>t;
    while(t--) solve();
    return 0;
}
 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号