HDU - 3038 - How Many Answers Are Wrong (带权并查集)

题意:有N个数字,M组关系。每组关系三个数字a,b,s表示a~b的和为s。问与前面产生矛盾的话有几组?

思路:带权并查集。多开一个权值数组,存储到自己和父节点的区间和。

图一:路径压缩,b~root的和 = b~a的和 + a ~ root的和。

图二:合并操作,现在我们知道a~root1和b~root2的区间和,又告诉了我们a~b的区间和,把root2并到root1上的话,

root1~root2的区间和为 (a~b)+ (b~root2) - (a~root1)。 

图三:求a~b的区间和,a~b的和 = (a~root) - (b ~ root)的和。


[cpp]  view plain  copy
  1. #include<bits/stdc++.h>  
  2. using namespace std;  
  3. const int MAXN = 200005;  
  4. int n, m, ans, f[MAXN], w[MAXN];//并查集数组和关系数组  
  5. //w[i]表示跟根节点的差  
  6. void init()  
  7. {  
  8.     ans = 0;  
  9.     for (int i = 0; i <= n; i++)  
  10.     {  
  11.         f[i] = i; w[i] = 0;  
  12.     }  
  13. }  
  14. int Find(int x)  
  15. {  
  16.     if (f[x] == x) return x;  
  17.     int t = f[x];  
  18.     f[x] = Find(f[x]);  
  19.     w[x] = w[x] + w[t];  
  20.     return f[x];  
  21. }  
  22. void Union(int a, int b, int s)  
  23. {  
  24.     int root1 = Find(a), root2 = Find(b);  
  25.     if (root1 != root2)  
  26.     {  
  27.         f[root1] = root2;  
  28.         w[root1] = w[b] + s - w[a];  
  29.     }  
  30.     else  
  31.     {  
  32.         if (abs(w[a] - w[b]) != s) ans++;  
  33.     }  
  34. }  
  35. int main()  
  36. {  
  37.     while(~scanf("%d%d", &n, &m))  
  38.     {  
  39.         init();//初始化  
  40.         while (m--)  
  41.         {  
  42.             int a, b, s;  
  43.             scanf("%d%d%d", &a, &b, &s);  
  44.             Union(a - 1, b, s);//a~b的区间和为w[b] - w[a - 1]  
  45.         }  
  46.         printf("%d\n", ans);  
  47.     }  
  48.     return 0;  
  49. }  
  50. /* 
  51. 10 5 
  52. 1 10 100 
  53. 7 10 28 
  54. 1 3 32 
  55. 4 6 41 
  56. 6 6 1 
  57. */  

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/79996935