HDU_4496_逆向并查集

http://acm.hdu.edu.cn/showproblem.php?pid=4496

逆向并查集,先读取,然后从后向前join每次保存答案即可。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int pre[10005],line[100005][2],ans[100005];

int findd(int x)
{
    int root = x;
    while(root != pre[root])    root = pre[root];
    int now = x,temp;
    while(now != pre[now])
    {
        temp = pre[now];
        pre[now] = root;
        now = temp;
    }
    return root;
}

int join(int x,int y)
{
    int xx = findd(x),yy = findd(y);
    if(xx == yy)    return 0;
    else
    {
        pre[xx] = yy;
        return 1;
    }
}

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i = 0;i < n;i++)    pre[i] = i;
        for(int i = 0;i < m;i++)
            scanf("%d%d",&line[i][0],&line[i][1]);
        int now = n;
        for(int i = m-1;i >= 0;i--)
        {
            ans[i] = now;
            if(join(line[i][0],line[i][1])) now--;
        }
        for(int i = 0;i < m;i++)    printf("%d
",ans[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhurb/p/5917638.html