poj 2230 Watchcow(欧拉回路)

关键是每条边必须走两遍,重复建边即可,因为确定了必然存在 Euler Circuit ,所以所有判断条件都不需要了。

注意:我是2500ms跑过的,鉴于这道题ac的code奇短,速度奇快,考虑解法应该不唯一。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<vector>
 4 #include<stack>
 5 #include<algorithm>
 6 #define rep(i,a,b) for(int i=a;i<=b;i++)
 7 #define clr(a,m) memset(a,m,sizeof(a))
 8 using namespace std;
 9 
10 const int MAXN=11111;
11 const int MAXM=55555;
12 
13 struct Edge{
14     int v,next,vis;
15     Edge(){}
16     Edge(int _v,int _next):v(_v),next(_next),vis(0){}
17 }edge[MAXM<<2];
18 
19 stack<int>stk;
20 int head[MAXN],tol;
21 int degree[MAXN];
22 
23 void init()
24 {
25     tol=0;
26     clr(head,-1);
27 }
28 
29 void add(int u,int v)
30 {
31     edge[tol]=Edge(v,head[u]);
32     head[u]=tol++;
33 
34     edge[tol]=Edge(u,head[v]);
35     head[v]=tol++;
36 }
37 
38 void FindEuler(int u)
39 {
40     for(int i=head[u];i!=-1;i=edge[i].next)
41     {
42         int v=edge[i].v;
43 
44         if(!edge[i].vis){
45             edge[i].vis=edge[i^1].vis=1;
46             FindEuler(v);
47             stk.push(v);
48         }
49     }
50 }
51 
52 void EulerCircuit(int n)
53 {
54     while(!stk.empty())
55         stk.pop();
56     FindEuler(0);
57 }
58 
59 int main()
60 {
61     int n,m,x,y;
62     scanf("%d%d",&n,&m);
63 
64     init();
65     clr(degree,0);
66     rep(i,0,m-1){
67         scanf("%d%d",&x,&y);
68         x--;y--;
69         add(x,y);
70         add(x,y);
71         degree[x]+=2;
72         degree[y]+=2;
73     }
74 
75     EulerCircuit(n);
76     stk.push(0);
77     while(!stk.empty())
78     {
79         x=stk.top();stk.pop();
80         printf("%d\n",x+1);
81     }
82     return 0;
83 }
View Code

 

posted @ 2013-08-13 11:04  Thousand Sunny  阅读(191)  评论(0编辑  收藏  举报