标签:ons return desc http 就是 链接 max 并查集 else
题目链接:http://poj.org/problem?id=1182
题目:
Description
Input
Output
Sample Input
100 7 1 101 1 2 1 2 2 2 3 2 3 3 1 1 3 2 3 1 1 5 5
Sample Output
3
思路:用一个3*N的数组来维护他们之间的关系,x+n为x的捕食者,x+2*n为x的猎物,因而当x与y的关系是同类的时候,需将他们+n、+2*n都一起合并为一个集合;当他们为捕食关系时,要将他们设为彼此的猎物。坑点为:不要用多组输入!!!
代码实现如下:
1 #include <cstdio> 2 3 const int maxn = 5e4 + 7; 4 int n, k, ans; 5 int d, x, y; 6 int fa[maxn * 3], r[maxn * 3]; 7 8 void init(int n) { 9 for (int i = 0; i < n; i++) { 10 fa[i] = i; 11 r[i] = 0; 12 } 13 } 14 15 int fi(int x) { 16 return fa[x] == x ? x : fa[x] = fi(fa[x]); 17 } 18 19 void unite(int x, int y) { 20 int p1 = fi(x), p2 = fi(y); 21 if (p1 == p2) return; 22 if (r[p1] > r[p2]) { 23 fa[p2] = p1; 24 } else { 25 fa[p1] = p2; 26 if (r[p1] == r[p2]) r[p2]++; 27 } 28 } 29 30 bool check(int x, int y) { 31 return fi(x) == fi(y); 32 } 33 34 int main() { 35 scanf("%d%d", &n, &k); 36 init(3 * n); 37 ans = 0; 38 for (int i = 0; i < k; i++) { 39 scanf("%d%d%d", &d, &x, &y); 40 x = x - 1, y = y - 1; 41 if (x < 0 || x >= n || y < 0 || y >= n) { 42 ans++; 43 continue; 44 } 45 if (d == 1) { 46 if (check(x, n + y) || check(x, 2 * n + y)) { 47 ans++; 48 } else { 49 unite(x, y); 50 unite(n + x, n + y); 51 unite(2 * n + x, 2 * n + y); 52 } 53 } else { 54 if (check(x, y) || check(x, y + 2 * n) || x == y) { 55 ans++; 56 } else { 57 unite(x, n + y); 58 unite(x + n, y + 2 * n); 59 unite(x + 2 * n, y); 60 } 61 } 62 } 63 printf("%d\n", ans); 64 return 0; 65 }
标签:ons return desc http 就是 链接 max 并查集 else
原文地址:https://www.cnblogs.com/Dillonh/p/8972632.html