跳到正文

题解

题解:AT_abc397_e [ABC397E] Path Decomposition of a Tree

syf_jrym约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

ABC397E

题目大意

给定一棵树,求是否能将树分割为 nn 条长度为 kk 的路径

思路:dfs

显然的,包含第 ii 个节点的路径有两种情况:

  • 只包含一个或零个子节点,可能包含父节点
  • 包含两个子节点,不可能包含父节点

那么我们令 dpxdp_x 代表:在将x的子树选完以后,包含x的那条路径已经选了多少个节点

令 cntcnt 为 xx 的子节点中未选完的个数,那么就有四种可能:

  1. cnt==0 cnt==0 , 意味着不需要选择子节点,那么 dpx=0dp_x=0

  2. cnt==1 cnt==1 :那么我们就直接选择那个子节点即可, dpx=dpx+dpsondp_x = dp_x + dp_{son}

  3. cnt==2 cnt==2 ,意味着是上面的第二种情况,需要选取两个子节点,令两个子节点分别为 son1,son2son1,son2 那么又有两种可能:

    • dpson1+dpson2+1==kdp_{son1} + dp_{son2} + 1 == k ,说明选择两个子节点正好能凑成一条长度为 kk 的路径,dpx=0dp_x = 0
    • 否则,就不能凑成长度为 kk 的路径,输出 NoNo
  4. cnt>2cnt>2 ,此时无论如何都不能将 xx 的子树选完,输出 NoNo

代码实现

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=500005;
int to[N],nxt[N],frt[N],dp[N],idx,n,m;
void add(int x,int y){
	to[++idx]=y;
	nxt[idx]=frt[x];
	frt[x]=idx;
}
void dfs(int x,int fa){
	int f=0;
	int tmp=0;
	vector<int>cnt;
	for(int i=frt[x];i;i=nxt[i]){
		int j=to[i];
		if(j==fa) continue;
		f=1;
		dfs(j,x);
		if(dp[j]!=0){
			cnt.push_back(dp[j]);
			++tmp;
		}
	}
	if(tmp>2||(tmp==2&&cnt[0]+cnt[1]+1!=m)){
		cout<<"No";
		system("pause");
		exit(0);
	}
	else if(tmp==1){
		dp[x]=cnt[0]+1;
	}
	if(tmp==0) dp[x]=1;
	dp[x]%=m;
}
signed main(){
	cin>>n>>m;
	for(int i=1;i<n*m;++i){
		int x,y;
		cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	dfs(1,0);
	cout<<"Yes";
	system("pause");
	return 0;
}


原文