How Many Answers Are Wrong HDU - 3038 (Classic weighted disjoint-set)

Title effect: a interval of length n, then m subintervals follow, the word format of each section is x, y, z represents [x, y], and is z. If the current interval and previous intervals and conflict, will be sentenced to the current range and wrong, and asked: how many intervals and will be sentenced wrong.

Solution to a problem: x, y, z represent the x start all the numbers to y and then x-1 says that from the (x-1, y] in the interval and we can x-1 to left section to find his left. points, while the right side of the interval y is also looking for his left endpoint, if both the left point equal (to l) then he is to the interval [l, y] split into [l, x-1] and [ x, y], we determine what intervals are not equal, and it is w [y] == w [x-1] + realtion.

If the left point are not equal, then we would be merged.

 

(A and B are the x and y root)

After the merger:

 

 

Then modify the weights  predetermined parent node B is A, that now is the root node of the tree B, x B, the path should have two, one is x-> A-> B, weight sum of w [x] + AB, the other is x-> y-> b and the sum of weights for the relation + w [y]

Both should be equal, so w [x] + AB = relation + w [y], so that AB = w [A] = w [y] -w [x] + relation.

code:

  

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+7;
int fa[N];
int w[N];
int find(int x){
    if(x==fa[x]) return x;
    else {
        int c=find(fa[x]);
        w[x]+=w[fa[x]];
        return fa[x]=c;
    }
}
bool unite(int x,int y,int relation){
    int fx=find(x),fy=find(y);
    if(fx!=fy){
        four [FY] = FX;
        and [fy] = a [x] -w [y] + relation;
        return  0 ;
    }
    else {
        return relation!=w[y]-w[x];
    }
}
int main(){
    int n,m;
    ios::sync_with_stdio(0);
    while(cin>>n>>m){
        for(int i=0;i<=n;i++) {
            four [c] = on;
            w[i]=0;
        }
        int ans=0;
        for(int i=1;i<=m;i++){
            int x,y,z;
            cin>>x>>y>>z;
            x--;
            if(unite(x,y,z)) ans++;
        }
        cout<<ans<<endl;
    }
    return 0;
 } 

 

Guess you like

Origin www.cnblogs.com/Accepting/p/12643848.html