寻找欧拉回路(套圈法)

  1 #include <iostream>
  2 #include <queue>
  3 #include <stack>
  4 #include <cstdio>
  5 #include <vector>
  6 #include <map>
  7 #include <set>
  8 #include <bitset>
  9 #include <algorithm>
 10 #include <cmath>
 11 #include <cstring>
 12 #include <cstdlib>
 13 #include <string>
 14 #include <sstream>
 15 #include <time.h>
 16 #define x first
 17 #define y second
 18 #define pb push_back
 19 #define mp make_pair
 20 #define lson l,m,rt*2
 21 #define rson m+1,r,rt*2+1
 22 #define mt(A,B) memset(A,B,sizeof(A))
 23 #define lowbit(x) (x&(-x))
 24 using namespace std;
 25 typedef long long LL;
 26 //const double PI = acos(-1);
 27 const int N=2e5+10;
 28 //const int M=1e6+10;
 29 const LL mod=1e9+9;
 30 const int inf = 0x3f3f3f3f;
 31 const LL INF=0x3f3f3f3f3f3f3f3fLL;
 32 const double esp=1e-10;
 33 const int MAXN=500010;
 34 int vis[N],top=0,head[N],ans[N],pre[N],vik[2*N],cnt=0;
 35 struct node
 36 {
 37     int u,v,next;
 38 }E[N*2];
 39 void add(int u,int v)
 40 {
 41     E[top].u=u;
 42     E[top].v=v;
 43     E[top].next=head[u];
 44     head[u]=top++;
 45 }
 46 int found(int x)
 47 {
 48     if(x==pre[x])return x;
 49     else return pre[x]=found(pre[x]);
 50 }
 51 void unite(int x,int y)
 52 {
 53     int fx=found(x);
 54     int fy=found(y);
 55     if(fx!=fy)pre[fx]=fy;
 56 }
 57 void dfs(int u)
 58 {
 59     while(head[u]!=-1)
 60     {
 61         if(!vik[head[u]])
 62         {
 63             vik[head[u]]=1;
 64             vik[head[u]^1]=1;
 65             int i=head[u];
 66             dfs(E[i].v);
 67             ans[cnt++]=i;
 68         }
 69         else head[u]=E[head[u]].next;
 70     }
 71 }
 72 int main()
 73 {
 74 #ifdef Local
 75     freopen("data.txt","r",stdin);
 76 #endif
 77     //ios::sync_with_stdio(false);
 78     //cin.tie(0);
 79     int n,m,u,v,flag=0,num=0;
 80     scanf("%d%d",&n,&m);
 81     mt(vis,0);
 82     mt(vik,0);
 83     mt(head,-1);
 84     for(int i=1;i<=n;i++)pre[i]=i;
 85     for(int i=1;i<=m;i++)
 86     {
 87         scanf("%d%d",&u,&v);
 88         add(u,v);
 89         add(v,u);
 90         unite(u,v);
 91         vis[u]++;vis[v]++;
 92     }
 93     for(int i=1;i<=n;i++)
 94     {
 95         if(vis[i]%2)flag=1;
 96     }
 97     for(int i=1;i<=n;i++)
 98     {
 99         if(pre[i]==i)num++;
100     }
101     if(num>1)flag=1;
102     if(flag)
103     {
104         puts("NO");return 0;
105     }
106     else
107     {
108         dfs(1);
109         puts("YES");
110         sort(ans,ans+m);
111         for(int i=0;i<m;i++)
112         {
113             printf("%d %d\n",E[ans[i]].u,E[ans[i]].v);
114         }
115     }
116     return 0;
117 #ifdef Local
118     cerr << "time: " << (LL) clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
119 #endif
120 }

 

posted @ 2017-06-14 01:51  Kcl886  阅读(980)  评论(0编辑  收藏  举报