Weighted disjoint-set template HDU - 3038

https://vjudge.net/problem/HDU-3038

TT write a string of numbers, not visible to FF
FF select an interval (repeat operation), TT this section and tell FF, then, and some of it is not right, so, there are some answers are contradictory, according to these contradictions find answers to the wrong number.
Note two things: 1, and a TT to be correct, if it is given before and not contradictory.
After 2, FF found a contradiction with the previous and the subsequent analysis and is no longer involved, directly been abandoned.

Blog: https: //www.cnblogs.com/liyinggang/p/5327055.html

https://blog.csdn.net/yjr3426619/article/details/82315133?tdsourcetag=s_pcqq_aiomsg

 

First you have to know the right path with compression wording:

int find(int x){
    if(pre[x]!=x){
        int y = pre[x];
        pre[x] = find(pre[x]);
        sum[x] += sum[y];
    }
    return pre[x];
}

There are weighted and search and collection:

 

 

pre[fa] = fb;
sum[fa] = -sum[a] + s + sum[b] ;

 

We use this question a sum [] array holds the distance from a point to its ancestor node.
By processing, sum weighted value of each node disjoint-set which is the value of the parent node points to the right
if the intermediate path experienced compression, is directed ancestor weight

Note that the given interval L and R may be the same, but can not use disjoint-set data structures to do this, so when depositing L- take - or R ++

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <algorithm>
#include <queue>
#define INF (1<<30)
using namespace std;

const int maxn = 2e5+7;
int sum[maxn];
int pre[maxn];

int find(int x){
    if(pre[x]!=x){
        int y = pre[x];
        pre[x] = find(pre[x]);
        sum[x] += sum[y];
    }
    return pre[x];
}

int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0; i<=n+1; i++){
            pre[i] = i;
            sum[i] = 0;
        }
        int fa,fb,a,b,s,ans=0;
        while(m--){
            scanf("%d%d%d",&a,&b,&s);
            b++;
            fa = find(a);
            fb = find(b);
            if(fa==fb){
                if(sum[a]!=s+sum[b]){
                    ans++;
                }
            }
            else{
                pre[fa] = fb;
                sum[fa] = -sum[a] + s + sum[b] ;
            }
        }
        printf("%d\n", ans);
    }
}

 

Guess you like

Origin www.cnblogs.com/-Zzz-/p/11469812.html