[HDU - 3038]How Many Answers Are Wrong
这是并查集很常见的题型。
对于A~B之间的和是S,其实可以理解成B比A-1大S;
这样和普通的并查集就很类似了。
#include <cstdio> #include <cstring> #include <iostream> using namespace std; #define maxn 200000 + 10 int father[maxn]; int val[maxn]; int Find(int x) { if (x == father[x]) return x; int temp = father[x]; father[x] = Find(father[x]); val[x] += val[temp]; return father[x]; } int n, m; int main() { while (~scanf("%d %d", &n, &m)) { for (int i = 1; i <= n; i++) { father[i] = i; val[i] = 0; } int ans = 0; for (int i = 1; i <= m; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); u -= 1; int ru = Find(u), rv = Find(v); if (ru == rv && val[u] + w != val[v]) ans++; else if (ru > rv) { father[ru] = rv; val[ru] = val[v] - val[u] - w; } else if (rv > ru) { father[rv] = ru; val[rv] = val[u] - val[v] + w; } } printf("%d\n", ans); } return 0; }