食物链类似的题,主要是在于转化,a-b的和为s,转换为b比a-1大s。然后并查集存 此节点到根的差。
假如x的根为a,y的根为b:
b - y = rank[y]
a - x = rank[x]
y - x = s
可以推出b - a = rank[y] - rank[x] + s;
并查集 延迟更新什么的,都忘了啊。
还有这题,如果是x--的话,记得更新0的根。
#include <cstring> #include <cstdio> #include <string> #include <iostream> #include <algorithm> #include <vector> #include <queue> using namespace std; int o[200001]; int rank[200001]; int find(int x) { if(x == o[x]) return x; int t = find(o[x]); rank[x] = rank[o[x]] + rank[x]; return o[x] = t; } int main() { int n,m,i,a,b,s,ans,x,y; while(scanf("%d%d",&n,&m)!=EOF) { for(i = 0;i <= n;i ++) { o[i] = i; rank[i] = 0; } ans = 0; for(i = 0;i < m;i ++) { scanf("%d%d%d",&x,&y,&s); x -- ; a = find(x); b = find(y); if(a != b) { o[a] = b; rank[a] = rank[y] - rank[x] + s; } else { if(rank[x] != rank[y] + s) ans ++; } } printf("%d\n",ans); } return 0; }
HDU 3038 How Many Answers Are Wrong(种类并查集),布布扣,bubuko.com
HDU 3038 How Many Answers Are Wrong(种类并查集)
原文:http://www.cnblogs.com/naix-x/p/3708373.html