Watchcow
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 |
欧拉回路标准求法
§任取一个起点,开始下面的步骤
(1)、如果该点没有相连的点,就将该点加进路径中然后返回。
(2)、如果该点有相连的点,就列一张相连点的表然后遍历它们直到该点没有相连的点。(遍历一个点,删除一个点)
(3)、处理当前的点,删除和这个点相连的边, 在它相邻的点上重复上面的步骤,把当前这个点加入路径中
该题路虽然是双向的但是每条路要求走两遍而且方向不能相同所以转化为有向图的两条边
#include<stdio.h>
#include<string.h>
struct node//存边
{
int to;//表示可以到的结点
int next;//存下个一u为起始点的路
int vis;//是否被走过
} edge[500100];
int cnt,head[10010];//head存路链表头
void adde(int u,int v)//u起点.v终点
{
edge[cnt].to=v;
edge[cnt].next=head[u];//head[u]为上个以u为起点的路的标号
edge[cnt].vis=0;
head[u]=cnt++;//cnt记录边的编号
}
void dfs(int u)//欧拉回路的标准求法
{
int i;
for(i=head[u];i;i=edge[i].next)
{
if(!edge[i].vis)
{
edge[i].vis=1;
dfs(edge[i].to);
}
}
printf("%d\n",u);//倒着打印路径
}
int main()
{
int m,n,u,v,i;
while(~scanf("%d%d",&n,&m))
{
memset(head,0,sizeof head);
cnt=1;
for(i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
adde(u,v);//添加边。转化为两条有向边
adde(v,u);
}
dfs(1);
}
return 0;
}