题目描述
Bessie’s been appointed the new watch-cow for the farm. Every night, it’s her job to walk across the farm and make sure that no evildoers are doing any evil. She begins at the barn, makes her patrol, and then returns to the barn when she’s done.
If she were a more observant cow, she might be able to just walk each of M (1 <= M <= 50,000) bidirectional trails numbered 1…M between N (2 <= N <= 10,000) fields numbered 1…N on the farm once and be confident that she’s seen everything she needs to see. But since she isn’t, she wants to make sure she walks down each trail exactly twice. It’s also important that her two trips along each trail be in opposite directions, so that she doesn’t miss the same thing twice.
A pair of fields might be connected by more than one trail. Find a path that Bessie can follow which will meet her requirements. Such a path is guaranteed to exist.输入格式
- Line 1: Two integers, N and M.
- Lines 2…M+1: Two integers denoting a pair of fields connected by a path.
输出格式
- Lines 1…2M+1: A list of fields she passes through, one per line, beginning and ending with the barn at field 1. If more than one solution is possible, output any solution.
输入样例
4 5
1 2
1 4
2 3
2 4
3 4输出样例
1
2
3
4
2
1
4
3
2
4
1
分析
题目大意给出n个点,m条边,要求从1号顶点出发走遍所有边,且每条边都要走两遍,每遍方向都相反。
显然这是一道有向欧拉回路输出裸题。参考Fleury算法思想,由于图中已经是欧拉回路了,所以直接dfs输出即可。
Fleury 算法
Fleury 算法是用于求无向图中欧拉回路的算法,其基本思想如下:
任取图 G 中一顶点 v0,令 P0=v0
假设沿 Pi=v0e1v1e2…eivi,走到顶点 vi,按下面的方法从 E(G)-{e1,e2,…,ei} 中选择 ei+1:
1)ei+1 与 vi 相关联
2)除非无别的边可供选择,否则 ei+1 不应是 Gi=G-{e1,e2,…,ei} 中的桥
当 2 不能再进行时,算法停止
可以证明的是,当算法停止时,所得到简单回路 Pm=v0e1v1e2…emvm(vm=v0) 为G中的欧拉回路
源程序
//#include <bits/stdc++.h> poj不能使用万能头
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAXN 50005
using namespace std;
struct Edge{
int v,next;
Edge(){};
Edge(int _v,int _next){
v=_v,next=_next;
};
}edge[MAXN*2];
int EdgeCount,head[MAXN];
int n,m;
bool used[MAXN*2];
int read()
{
int sum=0;
char c=getchar();
while(c<'0'||c>'9')c=getchar();
while(c>='0'&&c<='9'){
sum=sum*10+c-'0';
c=getchar();
}
return sum;
}
void add(int u,int v)
{
edge[++EdgeCount]=Edge(v,head[u]);
head[u]=EdgeCount;
}
void euler(int u)
{
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].v;
if(!used[i]){
used[i]=true;
euler(v);
}
}
printf("%d\n",u);
}
int main()
{
memset(head,0,sizeof(head));
memset(used,false,sizeof(used));
n=read(),m=read();
for(int i=1;i<=m;i++){
int x=read(),y=read();
add(x,y);
add(y,x);
}
euler(1);
return 0;
}