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

分析:
题目上要求的是从1号点出发,走过一个回路之后再回到1号点,但是要求的是同一条路径要按照相反的方向各走一遍,到这里我们必须理解到一点就是,对于图上的点来所,有且仅有一个点要走3次,其余的点都要走两次。
由于是无向边,而且每条边要求正反各走一次,所以一定存在欧拉回路。存图时把每条无向边看成两条相反的有向边,直接利用欧拉回路求解。
但是这样的路径走法可能有许多种,我们只需要输出其中一种即可。

代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m;
struct Node
{
    int next ;
    int to;
} node[100005];
int head[20009];
int Count=0;
void addEdg(int u,int v)//图正反方向都要存储一遍
{
    Count++;
    node[Count].to=v;
    node[Count].next=head[u];
    head[u]=Count;
    Count++;
    node[Count].to=u;
    node[Count].next=head[v];
    head[v]=Count;

}
bool vis[20009];
void dfs(int u)
{
    for(int i=head[u]; i ; i=node[i].next)
    {
        if(vis[i]==1)continue;//该边已经走过了,就不能够再走了
        vis[i]=1;
        dfs(node[i].to);
    }
    cout<<u<<endl;
}
int main()
{
    int u,v;
    scanf("%d%d",&n,&m);
    for(int i=0; i<m; i++)
    {
        scanf("%d%d",&u,&v);
        addEdg(u,v);
    }
    dfs(1);
    return 0;
}

posted on 2017-10-20 14:34  渡……  阅读(204)  评论(0编辑  收藏  举报