首页 > 代码库 > HYSBZ_1854_并查集

HYSBZ_1854_并查集

http://www.lydsy.com/JudgeOnline/problem.php?id=1854

 

每次判断每组两个数的根,若不等,则小的遍历1,大的为根,若相等,则说明前面的小的都遍历过,根遍历1。最后判断vis即可。

 

#include<iostream>#include<cstdio>using namespace std;int pre[1000005],vis[1000005] = {0};int findd(int x){    int root = x;    while(root != pre[root])    root = pre[root];    int temp;    while(x != pre[x])    {        temp = pre[x];        pre[x] = root;        x = temp;    }    return root;}void join(int x,int y){    int xx = findd(x),yy = findd(y);    if(xx == yy)    vis[xx] = 1;    else    {        if(xx > yy) swap(xx,yy);        pre[xx] = yy;        vis[xx] = 1;    }}int main(){    int n;    scanf("%d",&n);    for(int i = 1;i <= 100005;i++)   pre[i] = i;    while(n--)    {        int a,b;        scanf("%d%d",&a,&b);        join(a,b);    }    int i;    for(i = 1;i <= n;i++)    {        if(vis[i] == 0) break;    }    printf("%d",i-1);    return 0;}

 

HYSBZ_1854_并查集