• + 1 comment

    hey I guess I found your bug!

    void weightedu(long long int x ,long long int y){
       long long int i=findroot(x);
       long long int j=findroot(y);
       if(i != j) {
           id[j]=i;
           s[i]=s[i]+s[j];
           s[j]=0;
       }    
    }
    

    just change your weightedu method to this. You forgot an if check. your answers were coming wrong because in some cases when x and y belonged to the same country, you were doing the union and it was making the sum of that country 0.

    after fixing that when you run your code, you will get a timeout. that is because you have a nested loop inside calculating the answer. instead replace it with the simple efficient single loop.

    long long ans = 0;
    for(int i = 0; i < nodes; i++) {
        if(s[i] != 0) {
            ans += sum*s[i];
            sum += s[i];
        }
    }
    
    cout<<ans;
    

    and there you go! solved!