本文主要是介绍【HDU】How Many Answers Are Wrong(带权并查集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
num[i]代表i到根节点的值
这道题一开始竟然以为是线段树= =!后来发现线段树无法进行子区间的维护
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 222222;
int fa[maxn],num[maxn];
int find_father(int u){if(fa[u] == u)return fa[u];else{int temp = fa[u];fa[u] = find_father(fa[u]);num[u] += num[temp];return fa[u];}
}
int main(){int n,m;while(scanf("%d%d",&n,&m) != EOF){memset(num,0,sizeof(num));int cnt = 0;for(int i = 0; i <= n; i++) fa[i] = i;for(int i = 0; i < m; i++){int x,y,z;scanf("%d%d%d",&x,&y,&z);x --;int l = find_father(x),r = find_father(y);if(l == r){int e = num[y] - num[x];if(e != z){cnt ++;}}else{fa[r] = l;num[r] = z + num[x] - num[y];}}printf("%d\n",cnt);}return 0;
}
这篇关于【HDU】How Many Answers Are Wrong(带权并查集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!