跳到正文

题解

题解:P12621 [NAC 2025] Circle of Leaf

highkj约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月28日
收录
2026年7月23日
更新
2026年11月3日
篇幅
约 4 分钟
获赞
4
题目
P12621

版本

  1. v1当前

前言

因为这题的题号(比较有意义)所以做了。

nnn 还是太强了,膜拜。

思路

考虑树形 dp,我们定义 fi,0/1f_{i,0/1} 表示以 ii 为根的子树不考虑其上面的边是否与根联通的方案数,考虑转移。

  • 如果不删这条边,那么一定不能出现两棵子树都是 11 的情况,fx,0=fx,0×fto,0,fx,1=fx,1×fto,0+fto,1×fx,0f_{x,0}=f_{x,0}\times f_{to,0},f_{x,1}=f_{x,1}\times f_{to,0}+f_{to,1}\times f_{x,0}。
  • 如果断掉这条边,fx,1=fx,1×fto,1,fx,0=fx,0×fto,1f_{x,1}=f_{x,1}\times f_{to,1},f_{x,0}=f_{x,0}\times f_{to,1}。

然后把这两种情况合并一下就行了,注意要考虑一下更新的顺序,然后初始化就是如果是根则 fx,1=1f_{x,1}=1 否则如果是叶子节点则 fx,1=fx,0=1f_{x,1}=f_{x,0}=1 否则 fx,0=1f_{x,0}=1(毕竟它既不是根也不考虑上面的边)。

代码

C++
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define rep(i,x,y) for(register int i=x;i<=y;i++)
#define rep1(i,x,y) for(register int i=x;i>=y;--i)
#define int long long
#define fire signed
#define il inline
template<class T> il void print(T x) {
	if(x<0) printf("-"),x=-x;
	if (x > 9) print(x / 10);
	putchar(x % 10 + '0');
}
template<class T> il void in(T &x) {
    x = 0; char ch = getchar();
    int f = 1;
    while (ch < '0' || ch > '9') {if(ch=='-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
    x *= f;
}
int T=1;
const int N=2e5+10,mod=998244353;
vector<int>v[N];
int f[N][2],n;
void dfs(int x,int fa) {
	int cnt=0;
	if(x==1) {
		f[x][1]=1;
	}else {
		if(v[x].size()==1) f[x][0]=f[x][1]=1;
		else f[x][0]=1;
	}
	for(auto to:v[x]) {
		if(to==fa) continue;
		cnt++;
		dfs(to,x);
		f[x][1]=(f[x][1]*f[to][0]+f[x][0]*f[to][1]+f[x][1]*f[to][1])%mod;
		f[x][0]=(f[x][0]*f[to][0]+f[x][0]*f[to][1])%mod;
	}
}
void solve() {
	in(n);
	rep(i,1,n-1) {
		int a,b;
		in(a),in(b);
		v[a].pb(b);
		v[b].pb(a);
	}
	f[1][1]=1;
	dfs(1,0);
	printf("%lld\n",f[1][1]);
}
fire main() {
	while(T--) {
		solve();
	}
	return false;
}

行稳致远。

原文