您的位置:首页 > 其它

LA 3644 并查集判断无向图是否有环

2015-08-24 10:31 288 查看
理解清楚题意以后就明白为什么要用并查集了。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int N = 100001;
int f
;
int ans;

void init()
{
ans = 0;
for ( int i = 0; i < N; i++ )
{
f[i] = i;
}
}

int findf( int x )
{
if ( f[x] != x ) f[x] = findf( f[x] );
return f[x];
}

bool union_set( int x, int y )
{
x = findf(x), y = findf(y);
if ( x == y ) return false;
f[x] = y;
return true;
}

int main ()
{
int x, y;
while ( scanf("%d%d", &x, &y) != EOF )
{
init();
f[x] = y;
while ( scanf("%d", &x), x != -1 )
{
scanf("%d", &y);
if ( !union_set( x, y ) )
{
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: