HDU 1878 【欧拉回路】

  掌握无向图欧拉回路存在的充要条件:连通且所有点的度数为偶数。这里采用并查集判断是否连通,只要把每条边的两个顶点合并,最后判断是否有顶点不在这个集合里就可知是否连通。在并查集合并时没有判断要合并的顶点是否已经在一个集合中,导致产生集聚,多次TLE,自己真的很水啊。
View Code
   
     
#include < iostream >
#include
< cstring >

using namespace std;
const int MAX = 1005 ;

int n,m,degree[MAX],root[MAX];

void makeSet()
{
for ( int i = 1 ;i <= n; ++ i) root[i] = - 1 ;
}

int findSet( int x)
{
while (root[x] > 0 ) x = root[x];

return x;
}

void unionSet( int a, int b)
{
int x = findSet(a); int y = findSet(b);

if (x == y) return ;

if (root[x] > root[y])
{
root[y]
+= root[x];
root[x]
= y;
}
else
{
root[x]
+= root[y];
root[y]
= x;
}
}

int main()
{
int i,u,v;
while ( true )
{
cin
>> n;
if (n == 0 ) break ;
cin
>> m;

memset(degree,
0 , sizeof (degree));
makeSet();
for (i = 0 ;i < m; ++ i)
{
// cin>>u>>v;
scanf( " %d %d " , & u, & v);
degree[u]
++ ; degree[v] ++ ;
unionSet(u,v);

}

bool exist = true ;

for (i = 1 ;i <= n; ++ i)
{
if (degree[i] % 2 != 0 )
{
exist
= false ;
break ;
}
}

if (exist)
{
int counts = 0 ;

for (i = 1 ;i <= n; ++ i)
{
if (root[i] < 0 )
{
counts
++ ;
}

if (counts > 1 )
{
exist
= false ;
break ;
}
}
}

if (exist) cout << " 1 " << endl;
else cout << " 0 " << endl;
}

return 0 ;
}

你可能感兴趣的:(HDU)