并查集应用2

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1272

这个主要是 图的判连通 和 判不存在环 即可

#include <cstdio>  
#include <iostream>  
#include <cstring>  
#pragma comment(linker, "/STACK:102400000,102400000")  
using namespace std;  

const int MAXP = 100005;  
bool flag;  
int father[MAXP];  

void init(){  
    memset(father,-1,sizeof(father));  
    flag = true;  
}  

int find(int a){  
    if (father[a] <= 0)      return a;  
    return father[a] = find(father[a]);  
}  

void combination(int ra,int rb){  
    father[rb] = ra; //father[rb]一定为 0 或 -1  
    if ( father[ra] < 0 )  
        father[ra] = 0; // 只有-1有资格变成0  
}  

bool is_connected(){  
    int s=0;  
    for (int i =1; i < MAXP; i++)  
        if (father[i]==0)  
            s++;  
    if (s>1)return false;  
    else    return true;  
}  

int main()  
{  
    while(1){  
        int a,b,l=0;  
        init();  
        while(scanf("%d%d",&a,&b)&&a!=-1){  
            if (a<=0 && b<=0){  
                if (l==0)  
                    flag = true;  
                break;  
            }else{  
                int ra = find(a);  
                int rb = find(b);  
                if (ra == rb){ // they have same ancestor  
                    flag = false;  
                }else{  
                    combination(ra,rb);  
                }  
            }l++;  
        }  
        if (a==-1)break;  
        if (flag && is_connected()){  
            cout << "Yes" << endl;  
        }else{  
            cout << "No" << endl;  
        }  
    }  
    return 0; 
}
原文地址:https://www.cnblogs.com/cheng07045406/p/3108054.html