POJ 1703 Find them, Catch them (并查集)

题意:一共有N个人,给出M个操作分为两种:

1、A   a  b  :提问a和b是否是同一个帮派的。有三种答案:是,不是和不确定

2、D  a  b   :a和b不是同一个帮派的。

析:加权并查集,用一个r[i]来表示 i 和其父亲的关系,如果为0,表示 i 和其父亲是同一帮,1表示不是,每次更新即可。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<double, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e5 + 10;
const int mod = 1e6;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}
int p[maxn], r[maxn];
int Find(int x){
  if(x == p[x])  return x;
  int tmp = p[x];
  p[x] = Find(p[x]);
  r[x] = (r[x] + r[tmp]) % 2;
  return p[x];
}

int main(){
  int T;  cin >> T;
  while(T--){
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; ++i)  p[i] = i, r[i] = 0;
    char s[5];
    while(m--){
      int a, b;
      scanf("%s %d %d", s, &a, &b);
      if(s[0] == 'A'){
        int x = Find(a);
        int y = Find(b);
        if(x != y)  puts("Not sure yet.");
        else if(r[a] != r[b])  puts("In different gangs.");
        else  puts("In the same gang.");
      }
      else {
        int x = Find(a);
        int y = Find(b);
        if(x == y)  continue;
        p[y] = x;
        r[y] = (r[a] + r[b] + 1) % 2;
      }
    }
  }
  return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/6511891.html