POJ 2230 Watchcow 欧拉回路的DFS解法(模板题)
Watchcow
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 9974 Accepted: 4307 Special Judge
Description
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.
Input
-
Line 1: Two integers, N and M.
-
Lines 2…M+1: Two integers denoting a pair of fields connected by a path.
Output -
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.
Sample Input
4 5
1 2
1 4
2 3
2 4
3 4
Sample Output
1
2
3
4
2
1
4
3
2
4
1
Hint
OUTPUT DETAILS:
Bessie starts at 1 (barn), goes to 2, then 3, etc…
Source
USACO 2005 January Silver
这道题当时做的时候,觉得好难啊,学长说这是欧拉回路,然后我一想没学,后来在课程总结中发现原来学了,自己没注意。对全图进行dfs,从规定起点开始,过程中记录经过了哪些边,以保证每条边只经过一次。当一个点的所有边都遍历完成后,把该点入栈。最后依次弹栈得到的就是欧拉路径。被入栈的点都是走投无路的点,如果存在欧拉路径,第一次出现 没有边一定是在走回到起点时,因为其他情况无论怎么走只可能略过一些边,而不可能走进死路,所以若存在欧拉回路,必定在最后一个点的最后一条边回到起始点。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn 10005
const int maxm 100005
struct Edge
{
int v, next;
}edge[maxm];
int n, m;
int head[maxn];
int ecount;
bool vis[maxm];
void addedge(int a, int b) //接下一个边
{
edge[ecount].v = b;
edge[ecount].next = head[a];
head[a] = ecount++;
}
void dfs(int a)
{
for (int i = head[a]; i != -1; i = edge[i].next)
{
if (vis[i])
continue;
int v= edge[i].v;
vis[i] = true;
dfs(v);
}
printf("%d\n", a + 1); 从栈顶开始向下打印。
}
int main()
{
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
ecount = 0;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d %d", &a, &b);
a--;
b--;
addedge(a, b);
addedge(b, a);
}
dfs(0);
return 0;
}