您的位置:首页 > 其它

UVa 1160 X-Plosives(并查集)

2014-04-29 19:10 288 查看
题目链接:UVa 1160 X-Plosives

把元素当成顶点,把化合物当成边,当整个图存在环的时候,组成环的边对应的化合物是a powerful explosive,使用并查集判断加入一条边后是否存在环,如果存在,那么这条边不能加入。并查集一个集合中的点两两连通,如果两个元素已经属于一个集合,那么这两个元素间再加一条边肯定会出现环。

#include <iostream>
#include <cstdio>

using namespace std;

const int MAX_N = 100000 + 100;
int p[MAX_N];

int _find(int x)
{
    return x == p[x] ? x : (p[x] = _find(p[x]));
}
int main()
{
    int a, b, u, v, res;
    while(scanf("%d", &a) != EOF)
    {
        res = 0;
        for(int i = 0; i < MAX_N; i++)
            p[i] = i;
        while(a != -1)
        {
            scanf("%d", &b);
            u = _find(a);
            v = _find(b);
            if(u == v)
                res++;
            else
                p[u] = v;
            scanf("%d", &a);
        }
        printf("%d\n",res);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: