欧拉回路

https://www.cnblogs.com/acxblog/p/7390301.html

 

luogu p2731

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int N=510,M=2*1100;
 5 struct node{
 6     int x,y,next;
 7     bool bk;
 8 }a[M];
 9 int n,al,ql,first[N],degree[N],q[N];
10 
11 void ins(int x,int y)
12 {
13     a[++al].x=x;a[al].y=y;a[al].bk=1;
14     a[al].next=first[x];first[x]=al;
15 }
16 
17 void dfs(int x)
18 {
19     // printf("x = %d\n",x);
20     int nxt=n+1,id=0;
21     for(int i=first[x];i;i=a[i].next)
22     {
23         int y=a[i].y;
24         if(!a[i].bk) continue;
25         if(y<nxt) nxt=y,id=i;
26     }
27     if(id)
28     {
29         a[id].bk=0;
30         a[(id&1) ? id+1 : id-1].bk=0;
31         dfs(nxt);
32     }
33     q[++ql]=x;
34 }
35 
36 int main()
37 {
38     //freopen("a.in","r",stdin);
39     int m;
40     scanf("%d",&m);
41     al=0;
42     memset(first,0,sizeof(first));
43     memset(degree,0,sizeof(degree));
44     n=0;
45     for(int i=1;i<=m;i++)
46     {
47         int x,y;
48         scanf("%d%d",&x,&y);
49         n=max(n,max(x,y));
50         ins(x,y);ins(y,x);
51         degree[x]++;degree[y]++;
52     }
53     int st=n+1;
54     for(int i=1;i<=n;i++)
55     {
56         if(degree[i]&1) st=min(st,i);  
57     }
58     if(st==n+1) st=1;
59     ql=0;
60     dfs(st);
61     for(int i=ql;i>=1;i--) printf("%d ",q[i]);printf("\n");
62     return 0;
63 }

 

posted @ 2018-12-22 10:44 拦路雨偏似雪花 阅读(...) 评论(...) 编辑 收藏