标签:
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段,第一段表示A类,第二段表示B类,第三段表示C类
对每一个语句检查后加入到集合中
代码如下
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 8 int par[50002*3]; 9 int rank[50002*3]; 10 11 void init() { 12 memset(par, 0, sizeof(par)); 13 memset(rank,0, sizeof(rank)); 14 } 15 int find(int t) { 16 while(par[t] != 0) { 17 t = par[t]; 18 } 19 return t; 20 } 21 22 bool same(int x, int y) { 23 return find(x) == find(y); 24 } 25 26 void unite(int x, int y) { 27 x = find(x); 28 y = find(y); 29 if(x == y) return; 30 if(rank[x] < rank[y]) { 31 par[x] = y; 32 } 33 else { 34 par[y] = x; 35 if(rank[x] == rank[y]) { 36 rank[x]++; 37 } 38 } 39 } 40 41 int n, k; 42 int main(int argc, char const *argv[]) 43 { 44 //freopen("input.txt","r",stdin); 45 scanf("%d %d",&n,&k); 46 int ans = 0; 47 init(); 48 while(k--) { 49 int fa, x, y; 50 scanf("%d %d %d",&fa, &x, &y); 51 if(x > n || y > n || x <= 0 || y <= 0) { 52 ans++; 53 continue; 54 55 } 56 else if(fa == 1) { 57 if(same(x,y+n) || same(x, y+2*n)) { 58 //x eat y or y eat x 59 ans++; 60 continue; 61 } 62 else { 63 unite(x,y); 64 unite(x+n,y+n); 65 unite(x+2*n,y+2*n); 66 } 67 } 68 else if(fa == 2) { 69 if(same(x,y) || same(x, y + 2*n)) { 70 //x same y or y eat x 71 ans++; 72 continue; 73 } 74 else { 75 unite(x,y+n); 76 unite(x+n, y+2*n); 77 unite(x+2*n, y); 78 } 79 } 80 } 81 printf("%d\n",ans); 82 return 0; 83 }
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5792719.html