HDOJ1878(欧拉回路)

欧拉回路

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2516    Accepted Submission(s): 822


Problem Description
欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结
束。
 

Output
每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
 

Sample Input
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
 

Sample Output
1
0
//2009-05-12 17:37:32    Accepted    1878    46MS    236K    1346 B    C++
#include <iostream>
#include 
<set>
using namespace std;

const int N = 1003;

typedef 
struct
{
    
int parent;
    
int height;
}
node;

node UFSet[N 
* N];

void init(int cn)
{
    
for(int i = 0; i <= cn; i++)
    
{
        UFSet[i].parent 
= i;
        UFSet[i].height 
= 1;
    }

}


int find(int x)
{
    
while(x != UFSet[x].parent)
        x 
= UFSet[x].parent;
    
return x;
}


void merge(int x, int y)
{
    
if(x == y)
        
return ;

    
if(UFSet[x].height == UFSet[y].height)
    
{
        UFSet[y].parent 
= x;
        UFSet[x].height
++;
    }

    
else if(UFSet[x].height > UFSet[y].height)
        UFSet[y].parent 
= x;
    
else
        UFSet[x].parent 
= y;
}


int main()
{
    
int  cnt[N];
    
int n, m, cc;
    
int i, a, b;

    
while(scanf("%d"&n) && n)
    
{
        scanf(
"%d"&m);
        memset(cnt, 
0sizeof(cnt));
        init(n);
//并查集初始化

        
while(m--)
        
{
            scanf(
"%d%d"&a, &b);
            cnt[a]
++; cnt[b]++;
            a 
= find(a);
            b 
= find(b);
            merge(a, b);
            
        }


        
set<int> S;
        S.clear();

        cc 
= 0;

        
for(i = 1; i <= n; i++)
        
{
            
if(cnt[i] % 2)
                cc
++;//统计奇数度
            S.insert(find(i));
            
if(S.size() > 1)
                
break;
        }


        
if(S.size() > 1 || cc)
            printf(
"0\n");
        
else
            printf(
"1\n");
    }

    
return 0;
}

posted on 2009-05-12 18:03  Xredman  阅读(283)  评论(0编辑  收藏  举报

导航