hdu 1272 小希的迷宫(并查集)

来源:互联网 发布:socket.io.js 教程 编辑:程序博客网 时间:2024/06/06 01:43

1.是一个最小生成树

2.不能有环

如果输入的两个节点有相同的根节点,则说明有环

#include <iostream>#include <cstring>using namespace std;int f[100001];int book[100001];bool circle;int edge;int getf(int x){    return x == f[x] ? x:(f[x] = getf(f[x]));}void merge(int x, int y){    int t1 = getf(x);    int t2 = getf(y);    if(t1 != t2)    {        f[t2] = t1;        ++edge;    }    else        circle = true;}int main(){    int a,b,maxp,point;    while(cin >> a >> b && a != -1 && b != -1)    {        for(int i = 1; i <= 100001; ++i)            f[i] = i;        memset(book,0,sizeof(book));        point = 0;        circle = false;        maxp = 0;        edge = 0;        if(!(a+b))        {            cout << "Yes" << endl;            continue;        }        merge(a,b);        maxp = a > b ? a:b;        book[a] = book[b] = 1;        while(cin >> a >> b && (a+b))        {            maxp = maxp > a ? maxp:a;            maxp = maxp > b ? maxp:b;            book[a] = book[b] = 1;            merge(a,b);        }        for(int i = 1; i <= maxp; ++i)            if(book[i])                ++point;        if(point == edge+1 && !circle)            cout << "Yes" << endl;        else            cout << "No" << endl;    }    return 0;}


0 0
原创粉丝点击