IT民工
加油!

    这道题也是并查集的题,今天学校OJ又活了,想起暑假没A掉这道题,就去做了一下。题目要我们找出

和1号城市没有关联的城市,并查集处理后过一遍所有的城市,然后输出树根不是1的城市编号,没有就输出

0。写的时候发现一段时间不写差点忘了这两个函数是怎么写的!!!

#include<iostream>
#define MAX 250
using namespace std;

int p[MAX];

int find_set( int x )
{
return p[x] == x ? x : ( p[x] = find_set(p[x]) );
}

void union_set( int x, int y )
{
x = find_set(x);
y = find_set(y);
if( x == y ) return;
else if( x < y )
p[y] = x;
else if( x > y )
p[x] = y;
}

int main()
{
int n, m;
cin >> n >> m;
int a, b;
for( int i = 1; i <= n; i ++)
p[i] = i;
while( m -- )
{
cin >> a >> b;
union_set( a, b);
}
int cnt = 0;
for( int i = 1; i <= n; i ++)
if( find_set(p[i]) != 1) {
cout << i << endl;
cnt ++;
}
if( !cnt)
cout << cnt << endl;
return 0;
}


posted on 2011-10-30 17:47  找回失去的  阅读(234)  评论(0编辑  收藏  举报