这是一道求有向图欧拉回路的问题。
首先,介绍什么是欧拉回路。遍历图中的每条边,一次且仅一次,最后回到出发的点。
其次,介绍欧拉回路存在的条件。如果一个图存在欧拉回路,第一,是连通图;第二,如果是无向图,那么要求每个点的度为偶数,如果是有向图,那么要求每个点的入度等于出度。
最后,介绍一下解题思路,主要是深度优先搜索,用一个标识数组记录哪些边走过。不过在深搜过程中,要注意逆序记录节点,这个是保证算法正确性关键。因为算法的过程是一直向下搜索,直到不能继续搜索,此时这个节点肯定是出发的节点,记录下这个节点,然后回溯,回溯过程中如果有节点还有路没走,那么就继续搜索没走过的路,直到无路可走,再回溯,其中节点搜索的顺序和保存的路径顺序的对应关系想一想应该就会明白。如果先记录节点,再递归,顺序上肯定会有问题。(更详细的讲解可以参考《ACM—ICPC程序设计系列 图论及应用》(哈尔滨工业大学出版社)P20)
还有一点,这个算法只适合求欧拉回路,而不能求欧拉路径(即最后不必回到起点)。
随便说一下,这道一表明了是“Special Judge”,具体含义我不是太清楚,但是有两点可以确定:1)题目只有一组测试数据;2)答案不唯一,但只要符合题目要求都不会判错。
代码(C++):
#include <cstdlib>
#include <iostream>
#define MAXe 50005
#define MAXp 10005
using namespace std;
struct edge{
int to;
int next;
};
int head[MAXp],path[MAXe*2+1],amount;
edge array[MAXe*2];
bool vis[MAXe*2];
void dfs(int u)
{
int i;
for(i=head[u];i!=-1;i=array[i].next)
{
if(!vis[i])
{
vis[i]=true;
dfs(array[i].to);
}
}
path[--amount]=u;
}
int main(int argc, char *argv[])
{
int n,m,u,v,c,i;
while(cin>>n>>m)
{
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
c=0;
for(i=0;i<m;i++)
{
cin>>u>>v;
array[c].to=v;
array[c].next=head[u];
head[u]=c;
c++;
array[c].to=u;
array[c].next=head[v];
head[v]=c;
c++;
}
amount=m*2+1;
dfs(1);
for(i=0;i<m*2+1;i++) cout<<path[i]<<endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Time Limit: 3000MS | Memory Limit: 65536K | |||
Special Judge |
Description
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
* Lines 2..M+1: Two integers denoting a pair of fields connected by a path.
Output
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
Bessie starts at 1 (barn), goes to 2, then 3, etc...