POJ 3908 Quick answer 并查集

本题是并查集的运用,在删除操作时,除了该删除的点外其他连接关系不变,那么具体操作就将这个点变成新的点即可,用一个id数组更新id即可。
/*
ID: sdj22251
PROG: calfflac
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAX 100000000
#define LOCA
#define PI acos(-1.0)
using namespace std;
int pre[50005], id[50005];
int find(int x)
{
    if(pre[x] == x)
        return x;
    int t = find(pre[x]);
    pre[x] = t;
    return t;
}
void join(int x, int y)
{
    int fx = find(x);
    int fy = find(y);
    if(fx != fy)
    {
        if(fx > fy)
            pre[fx] = fy;
        else pre[fy] = fx;
    }
}
int main()
{
#ifdef LOCAL
    freopen("ride.in","r",stdin);
    freopen("ride.out","w",stdout);
#endif
    int n, i, n1, n2, x, y;
    char s[3];
    while(scanf("%d", &n) != EOF)
    {
        n1 = 0, n2 = 0;
        for(i = 1; i <= n; i++)
        {
            pre[i] = i;
            id[i] = i;
        }
        while(scanf("%s", s) != EOF)
        {
            if(s[0] == 'e')
                break;
            if(s[0] == 'c')
            {
                scanf("%d%d", &x, &y);
                join(id[x], id[y]);
            }
            else if(s[0] == 'd')
            {
                scanf("%d", &x);
                id[x] = ++n;
                pre[n] = n;
            }
            else if(s[0] == 'q')
            {
                scanf("%d%d", &x, &y);
                if(find(id[x]) == find(id[y]))
                    n1++;
                else n2++;
            }
        }
        printf("%d , %d\n", n1, n2);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值