avatar
fireworks99
keep hungry keep foolish

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

Description

有两个帮派,

给出 D a b 表示a和b位于不同帮派,

给出 A a b 表示询问a和b是否属于同一帮派

并查集

初始化一个 2 * N 的并查集,

如果a和b属于不同帮派,

unite(a, b + n) && unite(b, a + n)

这样如果c和b属于不同帮派

unite(c, b + n) && unite(b, c + n)

就把a和c连起来了

!!!什么神仙做法!!!

是不是暗示我们,有些题多用点空间就能解决问题

Code

#include <cstdio> #include <vector> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 100005; int n, m; int pre[N * 2]; void init() { for(int i = 0; i <= n * 2; ++i) pre[i] = i; } int found(int x) { if(pre[x] != x) pre[x] = found(pre[x]); return pre[x]; } void unite(int a, int b) { int x = found(a); int y = found(b); if(x != y) pre[x] = y; return ; } int main() { int t; scanf("%d", &t); while(t--) { char ch; int a, b; scanf("%d%d", &n, &m); getchar(); init(); while(m--) { ch = getchar(); scanf("%d%d", &a, &b); getchar(); if(ch == 'D') { unite(a, b + n); unite(b, a + n); } else { int x = found(a); // int xx = found(a + n); int y = found(b); int yy = found(b + n); if(x == y) cout << "In the same gang.\n"; else if(x == yy) cout << "In different gangs.\n"; else cout << "Not sure yet.\n"; } } } return 0; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy