POJ1703 并查集

2017年3月16日 | ljfcnyali
题目大意:Tadu City里面有两个黑帮团伙Gang Dragon和Gang Snake,一共有n名团伙成员(还不知道属于这两个黑帮的哪一个)。现在警察局有一些信息,每条信息包含2个人编号,表示这2个人属于不同的帮派。问给你2个人的编号,能否确定他们是否属于同一个帮派。

Sample Input

1 5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4

Sample Output

Not sure yet.
In different gangs.
In the same gang.

题目分析:并查集的应用。关键:用opp[x]表示一个与x处于不同帮派的人的编号,只需要1个就够了,因为只需要这么1个编号就能找出它的集合代表,若y的集合代表与之相同,则x与y为不同帮派。

AC代码:

/*************************************************************************
    > File Name: POJ1073.cpp
    > Author: ljf-cnyali
    > Mail: ljfcnyali@gmail.com 
    > Created Time: 2017/3/16 20:31:18
 ************************************************************************/

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<queue>

using namespace std;

#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)
#define mem(a) memset((a), 0, sizeof(a))
#define str(a) strlen(a)

const int maxn = 100050;

int n, m;

int f[maxn], w[maxn];

int cha(int x) {
    return x == f[x] ? x : f[x] = cha(f[x]);
}

void Set(int x, int y) {
    x = cha(x);
    y = cha(y);
    if(x == y)
        return ;
    else
        f[y] = x;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int t;
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &n, &m);
        mem(w);
        REP(i, 1, n)
            f[i] = i;
        int x, y;
        char c;
        REP(i, 1, m) {
            getchar();
            c = getchar();
            scanf("%d%d", &x, &y);
            if(c == 'D')
                if(w[x] == 0 && w[y] == 0) {
                    w[x] = y;
                    w[y] = x;
                }
                else if(w[x] == 0) {
                    w[x] = y;
                    Set(x, w[y]);
                }
                else if(w[y] == 0) {
                    w[y] = x;
                    Set(y, w[x]);
                }
                else {
                    Set(x, w[y]);
                    Set(y, w[x]);
                }
            else
                if(cha(x) == cha(y))
                    printf("In the same gang.\n");
                else if(cha(x) == cha(w[y]))
                    printf("In different gangs.\n");
                else
                    printf("Not sure yet.\n");
        }
    }
    return 0;
}

本文转自:http://ljf-cnyali.cn/index.php/archives/37

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值