跳到正文

题解

题解:CF405E Graph Cutting

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

文章信息

发布
2024年8月23日
收录
2026年5月15日
更新
2026年11月15日
篇幅
约 2 分钟
题目
CF405E

版本

  1. v2当前
  2. v1

题目分析

在图上直接做显然不好做,所以考虑在一棵生成树上求解。

最后我们会发现在 DFS 树上最好求,如过连向儿子的边内部能两两配对就内部完成,否则就跟一条返祖边配对。这样子树内就没有剩余,一定能配对成功。

在最开始判一下奇数无解即可。

时间复杂度 O(n)O(n)。

Code

C++
#include<bits/stdc++.h>
using namespace std;
//
const int maxn=1e5+10;
int n,m;
unordered_map<int,int>cut[maxn];
int deg[maxn],p[maxn];
vector<int> g[maxn];
int cnt;
struct Ans{
	int x,y,z;
}ans[maxn];
int dep[maxn];
void dfs(int u,int fa){
	int p1=0,p2=0;
	dep[u]=dep[fa]+1;
	for(int v:g[u]){
		if(!dep[v]){
			dfs(v,u);
		}
		if(dep[v]<dep[u])continue ;
		if(!cut[u][v]){
			if(!p1)p1=v;
			else{
				p2=v;
				ans[++cnt]={p1,u,p2};
				p1=p2=0;
			}
		}
	}
	if(p1){
		for(int v:g[u]){
			if(dep[v]<dep[u]){
				p2=v;
				cut[u][v]=cut[v][u]=1;
				ans[++cnt]={p1,u,p2};
				break ;
			}
		}
	}
}
int main(){
	cin>>n>>m;
	for(int i=1,x,y;i<=m;i++){
		cin>>x>>y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	if(m&1){
		cout<<"No solution\n";
		return 0;
	}
	dfs(1,0);
	for(int i=1;i<=cnt;i++)cout<<ans[i].x<<' '<<ans[i].y<<' '<<ans[i].z<<'\n';

	return 0;
}
原文