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).
- #include<bits/stdc++.h>
- usingnamespace std;
- const int MAXN = 200005;
- int n, m, ans, f[MAXN], w[MAXN]; //Union search array and relational array
- //w[i] represents the difference from the root node
- void init()
- {
- years = 0;
- for (int i = 0; i <= n; i++)
- {
- f[i] = i; w[i] = 0;
- }
- }
- int Find(int x)
- {
- if (f[x] == x) return x;
- int t = f[x];
- f[x] = Find(f[x]);
- w[x] = w[x] + w[t];
- return f[x];
- }
- void Union(int a, int b, int s)
- {
- int root1 = Find(a), root2 = Find(b);
- if (root1 != root2)
- {
- f[root1] = root2;
- w[root1] = w[b] + s - w[a];
- }
- else
- {
- if (abs(w[a] - w[b]) != s) ans++;
- }
- }
- intmain ()
- {
- while(~scanf("%d%d", &n, &m))
- {
- init(); //initialization
- while (m--)
- {
- int a, b, s;
- scanf("%d%d%d", &a, &b, &s);
- Union(a - 1, b, s); //The interval sum of a~b is w[b] - w[a - 1]
- }
- printf("%d\n", ans);
- }
- return 0;
- }
- /*
- 10 5
- 1 10 100
- 7 10 28
- 1 3 32
- 4 6 41
- 6 6 1
- */