Disjoint-set Hdu 1272

HDU 1272

That is: given a plurality of sets of data
are given 0,0, given before the start of the processing, can not form a ring, only one root
is given -1-1 end

Can form a ring: adding a join function inside judgment flag Flag
only a root node: determining the number of cycles is given, the number of the root node, cnt is only 1

Note 1: The data presented are not consecutive numbers, so there must be a given number of array tag vis
Note 2: 0,0 should be only to Yes

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 100005;
typedef long long ll;
int pre[maxn];
bool vis[maxn];
bool flag = 0;
int find(int x){
    int r = x;
    while(r!=pre[r])
        r = pre[r];
    while(x!=r){
        int t = pre[x];
        pre[x] = r;
        x = t;
    }
    return r;
}
void join(int x,int y){
    int fx = find(x);
    int fy = find(y);
    if(fx!=fy)
        pre[fx]  = fy;
    else{
        flag = 1;
    }
}
int main(){
    int x,y;
    while(~scanf("%d %d",&x,&y)){   //读入第一个
        if(x==-1 && y==-1)      //跳出
            break;
        if(x==0 && y==0){
            printf("Yes\n");
            continue;
        }
        memset(vis,0,sizeof(vis));
        for(int i=0; i<maxn; i++)
            pre[i] = i;

        int mmax = max(x,y);
        join(x,y);
        flag = 0;
        vis[x] = vis[y] = 1;
        
        while(scanf("%d %d",&x,&y) && x && y){      //读入剩下数据直到0 0
            mmax = max(mmax,max(x,y));
            join(x,y);
            vis[x] = vis[y] = 1;
        }
        //不能成环
        if(flag){
            printf("No\n");
            continue;
        }
        //只能有一个父节点
        int cnt = 0;
        for(int i=1; i<=mmax; i++)
            if(vis[i] && pre[i] == i)
                cnt++;
        if(cnt==1)
            printf("Yes\n");
        else
            printf("No\n");

    }
    return 0;
}

Published 62 original articles · won praise 0 · Views 1738

Guess you like

Origin blog.csdn.net/jhckii/article/details/104565179
Recommended