标签:
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
算法思路:
在原有parent[]的基础上加上另一关系relative[x],用于表示动物x相对于其根节点的关系:
对于偏移量的计算,分为两种情况:1、x,y在同一集合里(即根结点相同),此时判断真假即可;2、x,y在不同集合里,此时应把x,y归到同一集合下;
还不明白,可以参考这个有耐心的大神http://blog.sina.com.cn/s/blog_626633790100ut9j.html
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<list> 5 using namespace std; 6 const int maxn = 50010; 7 int ans; 8 struct Animal 9 { 10 int relative; /*relative = 0, 相对于根结点是同类; 11 relative = 1, 相对于根结点是吃; 12 relative = 2, 相对于根结点是被吃;*/ 13 int parent; 14 }animal[maxn]; 15 void MakeSet(int SizeOfSet) 16 { 17 for(int i = 0; i <= SizeOfSet; i++) 18 { 19 animal[i].parent = i; 20 animal[i].relative = 0; 21 } 22 } 23 int Find(int x) 24 { 25 int r = x; 26 if(animal[r].parent == r) return r; 27 int tmp = animal[x].parent; 28 animal[x].parent = Find(tmp); 29 animal[x].relative = (animal[x].relative + animal[tmp].relative) % 3; 30 return animal[x].parent; 31 } 32 void Solve(int d, int x, int y, int n) 33 { 34 if((d == 2 && x == y) || x > n || y > n) {ans++; return;} 35 int rootx = Find(x), rooty = Find(y); 36 if(rootx == rooty)//结点x, y在一个集合里 37 { 38 if(d == 1) 39 { 40 if(animal[x].relative != animal[y].relative) ans++; 41 } 42 else if(d == 2) 43 { 44 if((animal[x].relative + 1) % 3 != animal[y].relative) ans++; 45 } 46 } 47 else 48 { 49 animal[rooty].parent = rootx; 50 if(d == 1) 51 { 52 animal[rooty].relative = (animal[x].relative - animal[y].relative + 3) % 3; 53 } 54 else if(d == 2) 55 { 56 animal[rooty].relative = ((animal[x].relative + 1) % 3 - animal[y].relative + 3) % 3; 57 } 58 } 59 } 60 int main() 61 { 62 int n, k; 63 scanf("%d%d", &n, &k); 64 MakeSet(n); 65 while(k--) 66 { 67 int d, x, y; 68 scanf("%d%d%d", &d, &x, &y); 69 Solve(d, x, y, n); 70 } 71 printf("%d\n", ans); 72 return 0; 73 }
标签:
原文地址:http://www.cnblogs.com/LLGemini/p/4256117.html