c++disjoint-setsdisjoint-union

Disjoint set union implementation using c++


I am implementing Disjoint-Set Union by Rank and Path Compression in c++ according to the cp algorithm.But here I am getting an error reference to 'rank' is ambiguous . I have read many articles about this error but could not get any satisfactory answer.Can anyone help me with the problem?Thanks in advance.

#include<bits/stdc++.h>
using namespace std;
#define mx 10005
int parent[mx],rank[mx];

void make_set(int v) {
    parent[v] = v;
    rank[v] = 0;
}
int find_set(int v) {
    if (v == parent[v])
        return v;
    return parent[v] = find_set(parent[v]);
}

void union_sets(int a, int b) {
    a = find_set(a);
    b = find_set(b);
    if (a != b) {
        if (rank[a] < rank[b])
            swap(a, b);
        parent[b] = a;
        if (rank[a] == rank[b])
            rank[a]++;
    }
}
bool check(int a, int b){ return find_set(a) == find_set(b); }

int main()
{
    int x;cin>>x;
    for(int i=1;i<=x;++i)
    {
        make_set(i);
    }
    union_sets(1,2);
    union_sets(2,3);
    union_sets(4,5);
    union_sets(6,7);
    union_sets(5,6);
    union_sets(3,7);
    for(int i=1;i<=x;++i)
    {
        cout<<find_set(i)<<endl;
    }

}

Solution

  • using namespace std; sets you up for trouble, as it creates the opportunity for names to be the same as yours. Namespaces are in place to protect name collisions. In your case, std::rank is a name. Delete using namespace std; and you should fix the problem. See Why is "using namespace std;" considered bad practice?.

    Another bad practice in your code: Why should I not #include <bits/stdc++.h>?.