The 15th Chinese Northeast Collegiate Programming Contest C. Vertex Deletion(树形dp)

简介: The 15th Chinese Northeast Collegiate Programming Contest C. Vertex Deletion(树形dp)

linkkkk

题意:

给出一棵树,每次可以删去任意点,要求删完后不能有孤立的点,求方案数。

思路:

大概很容易看出来是个树形dp,状态不太好想。

d p [ u ] [ 0 ]表示删去这个点

d p [ u ] [ 1 ]表示不删这个点,而且删去所有子节点

d p [ u ] [ 2 ] 表示不删这个点,而且至少留一个子节点

对于第一种情况,此时的u一定满足条件;

对于第二种情况,要求u的父亲节点也不被删去才可以满足条件;

对于第三种情况,此时的u已经满足条件了。

转移的话:

dp[u][0]=(dp[t][0]+dp[t][2])%mod*dp[u][0]%mod;
dp[u][1]=dp[u][1]*dp[t][0]%mod;

如果删去u的话,那么想让子节点t满足条件,可以删除t,也可以不删t并且至少保留t的一个子节点;

如果不删u并且删去所有子节点的话,说明节点t是被删除的状态。

对于d p [ u ] [ 2 ]可以用所有合法的方案数减去不合法的方案数。

最后答案就是d p [ 1 ] [ 0 ] + d p [ 1 ] [ 2 ]

代码:

const int maxn=1e5+7,inf=0x3f3f3f3f;
const ll mod=998244353;
const double eps=1e-5;
vector<int>g[maxn];
ll dp[maxn][3],n;
void dfs(int u,int fa){
  dp[u][0]=dp[u][1]=dp[u][2]=1;
  for(auto t:g[u]){
    if(t==fa) continue;
    dfs(t,u);
    dp[u][0]=(dp[t][0]+dp[t][2])%mod*dp[u][0]%mod;
    dp[u][1]=dp[u][1]*dp[t][0]%mod;
    dp[u][2]=(dp[t][0]+dp[t][2]+dp[t][1])%mod*dp[u][2]%mod; 
  }
  dp[u][2]=(dp[u][2]-dp[u][1])%mod;
}
int main(){
  int _=read;
  while(_--){
    n=read;
    rep(i,1,n-1){
      int u=read,v=read;
      g[u].push_back(v);
      g[v].push_back(u);
    }
    dfs(1,-1);
    ll ans=dp[1][0]+dp[1][2];
    ans=(ans+mod)%mod;
    printf("%d\n",ans);
    rep(i,1,n) g[i].clear(),dp[i][0]=dp[i][1]=dp[i][2]=0;
  }
    return 0;
}
目录
相关文章
|
机器学习/深度学习
The Preliminary Contest for ICPC China Nanchang National Invitational J题 Distance on the tree
The Preliminary Contest for ICPC China Nanchang National Invitational J题 Distance on the tree
93 0
The Preliminary Contest for ICPC China Nanchang National Invitational A题 PERFECT NUMBER PROBLEM
The Preliminary Contest for ICPC China Nanchang National Invitational A题 PERFECT NUMBER PROBLEM
70 0
German Collegiate Programming Contest 2019 B . Bouldering (最短路)
German Collegiate Programming Contest 2019 B . Bouldering (最短路)
101 0
German Collegiate Programming Contest 2019 B . Bouldering (最短路)
AtCoder Beginner Contest 133 E - Virus Tree 2(组合数学)
AtCoder Beginner Contest 133 E - Virus Tree 2(组合数学)
104 0
|
算法
AtCoder Beginner Contest 213 E - Stronger Takahashi(01BFS)
AtCoder Beginner Contest 213 E - Stronger Takahashi(01BFS)
135 0
|
机器学习/深度学习
AtCoder Beginner Contest 215 E - Chain Contestant (状压dp)
AtCoder Beginner Contest 215 E - Chain Contestant (状压dp)
120 0
|
机器学习/深度学习 人工智能 BI
The 15th Chinese Northeast Collegiate Programming Contest
The 15th Chinese Northeast Collegiate Programming Contest
142 0
|
人工智能
Nordic Collegiate Programming Contest 2020 D.Damsindistress (dp)
Nordic Collegiate Programming Contest 2020 D.Damsindistress (dp)
94 0
AtCoder Beginner Contest 226 E - Just one(dfs求连通块 组合数学)
AtCoder Beginner Contest 226 E - Just one(dfs求连通块 组合数学)
105 0