跳到正文

题解

题解 CF1929D Sasha and a Walk in the City

zhicheng约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年2月21日
收录
2026年12月1日
更新
2026年12月1日
篇幅
约 2 分钟
获赞
13
题目
CF1929D

版本

  1. v1当前

思路

考虑 DP。设 dpudp_u 表示 uu 这个点所在子树中选点的方案数,满足任意两个点都没有祖先-后代关系。有:

dpu=∏v∈sonu(dpv+1)dp_u=\prod_{v\in son_u}(dp_v+1)

表示 vv 这个子树可以选某个方案或根本不选。答案就是 1+∑i=1ndpi1+\sum\limits_{i=1}^{n}dp_i。

为什么这个是正确的呢?考虑我们钦定 uu 的儿子中如果一个点都没有选或只有一个子树选了点就把 uu 选上(只有仅选 uu 时会向上传)。这样可以保证不重不漏。最后再加上一个点都不选的方案即可。

Code

C++
#include<bits/stdc++.h>
using namespace std;
const int N=300010,mod=998244353;
int n,ans,tot,first[N],nnext[N<<1],to[N<<1],dp[N];
void add(int x,int y){
	nnext[++tot]=first[x];
	first[x]=tot;
	to[tot]=y;
}
void dfs(int u,int fa){
	dp[u]=1;
	for(int e=first[u];e;e=nnext[e]){
		if(to[e]!=fa){
			dfs(to[e],u);
			dp[u]=1ll*dp[u]*(dp[to[e]]+1)%mod;
		}
	}
	ans=(ans+dp[u])%mod;
}
int main(){
	int t,a,b;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		tot=ans=0;
		for(int i=1;i<=n;i++){
			first[i]=0;
		}
		for(int i=1;i<=n-1;i++){
			scanf("%d%d",&a,&b);
			add(a,b);
			add(b,a);
		}
		dfs(1,0);
		printf("%d\n",(ans+1)%mod);
	}
}
原文
抓取于
  1. oceanfish

    好简明的思路

  2. GGapa

    推荐一个网址:https://cfstep.com/codeforces/contests/contest-1929/problem-d/hints/

  3. Meatherm

    你很牛