首页 > 代码库 > HDU 3047 Zjnu Stadium 带权并查集

HDU 3047 Zjnu Stadium 带权并查集

gg,y一下就是每个点到根的距离用rank维护,,

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <math.h>
#include <set>
using namespace std;
#define mod 1000000007
#define ll int
#define rank Rank
#define N 100100
ll n;
ll f[N], rank[N];
ll find(ll x){
    if(x==f[x]) return x;
    int t = f[x];
    f[x] = find(f[x]);
    rank[x] += rank[t];
    return f[x];
}
bool Union(int x, int y, int m){
    int fx = find(x), fy = find(y);
    if(fx==fy)
    {
        if(rank[x] + m != rank[y])
            return false;
        return true;
    }
    f[fy] = fx;
    rank[fy] = rank[x] + m -rank[y];
    return true;
}
void init(){
    for(int i = 0; i <= n; i++)
        f[i] = i, rank[i] = 0;
}
int main(){
	int i, j, u, v, d, que;
	while(~scanf("%d %d",&n,&que)) {
        init();
        int ans = 0;
        while(que--)
        {
            scanf("%d %d %d",&u,&v,&d);
            if(Union(u,v,d)==false)
                ans++;
        }
        cout<<ans<<endl;
	}
	return 0;
}
/*


*/