题目地址


基本思想:

  • 由于每条边只经过一次,遍历并删边即可.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=2e5,MAXM=2e5;
struct Edge{
	int from,to,nxt;
}e[MAXM];
int head[MAXN],edgeCnt=1;
void addEdge(int u,int v){
	e[++edgeCnt].from=u;
	e[edgeCnt].to=v;
	e[edgeCnt].nxt=head[u];
	head[u]=edgeCnt;
}
int stack[MAXN], ans[MAXN]; // 模拟系统栈,答案栈
bool vis[MAXN];
int top,t;
void euler() {
	stack[++top] = 1;
	while (top) {
		int x = stack[top], i = head[x];
		while (i && vis[i]) i = e[i].nxt;
		if (i) {
			stack[++top] = e[i].to;
			head[x] = e[i].nxt;
			vis[i]=vis[i^1]=1;
		}else{
			top--;
			ans[++t] = x;
		}
	}
}
int main() {
	int n,m;
	scanf("%d%d",&n,&m);
	for (int i = 1; i <= m; i++) {
		int u,v;
		scanf("%d%d",&u,&v);
		addEdge(u,v);
		addEdge(v,u);
	}
	euler();
	for (int i = 1; i<=t; i++) 
		printf("%d\n", ans[i]);
	return 0;
}