poj1703 并查集,食物链那样的题

题目意思好懂得很,就不再啰嗦。

并查集:以前一直只是简单地在图上用过,现在见到这种类别偏移的题这不是很好做啊。。。
主要思想就是要把一种物质的两面都建立起来,这样就能很好判断了;
这个题就是将两个帮派的人维护起来,并联系到两种形态;
如1,2是对立的帮派,那么1和2 + n就是一派的,2和1 + n就是一派的;
然后就这样建立并查集;

这题有坑就是只有两人时,那么这两人就是两个帮派的,因为这是题上说的“每个帮派至少一人”;

代码如下:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>

#define maxn 100100
#define INF 1e7
#define ll long long

using namespace std;

typedef pair<ll, ll> P;

int a[maxn * 2];

int find(int x)
{
    if (a[x] == x)
        return x;
    return a[x] = find(a[x]);
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int n, t;
        scanf("%d%d", &n, &t);
        for (int i = 1; i <= 2 * n; ++i)
        {
            a[i] = i;
        }
        while(t--)
        {
            char str[10], ch;
            int x, y;
            scanf("%s%d%d", str, &x, &y);
            ch = str[0];
            int x1,y1;
            int x2,y2;
            x1 = find(x), y1 = find(n + x);
            x2 = find(y), y2 = find(n + y);
            if (ch == 'D')
            {
                a[y2] = x1;
                a[y1] = x2;
            }
            else
            {
                if (n == 2)
                {
                    printf("In different gangs.\n");
                    continue;
                }
                if (x1 == x2 && y1 == y2)
                    printf("In the same gang.\n");
                else if (x1 == y2 || x2 == y1)
                    printf("In different gangs.\n");
                else
                    printf("Not sure yet.\n");
            }
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值