HDU - 3038 - How Many Answers Are Wrong

Question meaning: There are N numbers and M groups of relationships. Each group of three numbers a, b, s means that the sum of a~b is s. Q How many groups of words are in conflict with the previous ones?

Idea: take the right and check the set. Open an additional weight array, and store the interval sum to itself and the parent node.

Figure 1: Path compression, sum of b~root = sum of b~a + sum of a~root.

Figure 2: Merge operation, now we know the interval sum of a~root1 and b~root2, and tell us the interval sum of a~b. If root2 is merged into root1,

The interval sum of root1~root2 is (a~b) + (b~root2) - (a~root1). 

Figure 3: Find the interval sum of a~b, the sum of a~b = the sum of (a~root) - (b~root).


[cpp]  view plain copy  
  1. #include<bits/stdc++.h>  
  2. usingnamespace std;   
  3. const int  MAXN = 200005;   
  4. int  n, m, ans, f[MAXN], w[MAXN]; //Union search array and relational array  
  5. //w[i] represents the difference from the root node  
  6. void init()  
  7. {  
  8.     years = 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. intmain  ()  
  36. {  
  37.     while(~scanf("%d%d", &n, &m))  
  38.     {  
  39.         init(); //initialization  
  40.         while (m--)  
  41.         {  
  42.             int a, b, s;  
  43.             scanf("%d%d%d", &a, &b, &s);  
  44.             Union(a - 1, b, s); //The interval sum of a~b is 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. */  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325960977&siteId=291194637