1

I was solving a problem of Hackerrank in Graphs a particular question https://www.hackerrank.com/challenges/journey-to-the-moon/problem

I applied DSU but the answer is wrong even though the code is working for some test cases.

void make(int item)
{
    parent[item]=item;
    siz[item]=1;
}
int find(int a)
{
    if(parent[a]==a)
        return parent[a];
    else
    {
        parent[a]=find(parent[a]);
        return parent[a];
    }
}
void Union(int a,int b)
{
    a=find(a);
    b=find(b);
    if(a==b)
        return;
    else
    {
        if(siz[a]>siz[b])
        {
            parent[b]=a;
            siz[a]+=siz[b];
        }
        else
        {
            parent[a]=b;
            siz[b]+=siz[a];
        }
    }
}
int journeyToMoon(int n, vector<vector<int>> astronaut)
{
    for(int i=0;i<n;i++)
    {
        make(i);
    }
    for(int i=0;i<astronaut.size();i++)
    {
        Union(astronaut[i][0],astronaut[i][1]);
    }
    map<int,int> mp;
    for(int i=0;i<n;i++)
    {
        mp[parent[i]]++;
    }
    int cmp=0;
    for(auto it=mp.begin();it!=mp.end();it++)
    {
        for(auto jt=mp.begin();jt!=mp.end();jt++)
        {
            if(jt==it)
                continue;
            else
            {
              cmp=cmp+it->second*jt->second;  
            }
        }
    }
return cmp/2;
}

It is giving partially correct I think the logic is right but the solution has some problem

Test Case : 10 7 0 2 1 8 1 4 2 8 2 6 3 5 6 9 My Output->29 Actual Output->23

Xiao
  • 21
  • 1
  • 4
  • 1) What does Hackerrank complain about: wrong solution or time exceeded? 2) Please post a minimal reproducible example so others can easily test your code. 3) Say you can count how many pairs of astronauts `p` and how many single astronauts `s` there are; total number of astronauts is known, `n`; wouldn't you be able then to compute the solution using some combinatorics formula? This way you would only need to use a `std::set st` of paired astronauts, walk the pairs, and get `s = n - st.size()`. 4) `cmp=cmp+(*it).second*(*jt).second` would read better as `cmp = cmp + it->second * jt->second`. – rturrado Jan 10 '22 at 09:32
  • Edited: (*it).second and (*jt).second to it->second and jt->second – Xiao Jan 10 '22 at 12:48
  • I tried out the combinatorics formula of '(a*b) + (a+b)*c + (a+b+c)*d ....' but that too is giving the wrong ans; I tried your solution too but That too is not working. – Xiao Jan 10 '22 at 12:57
  • 1
    The problem boils down to finding connected components of an undirected graph. A simple search (breadth-first or depth-first, doesn't matter) can do that. Once you discovered all connected components `Ci` of sizes `Si`, the answer is `Sum(Si*Sj)` over all pairs `(i, j)`. – Igor Tandetnik Jan 10 '22 at 15:12
  • 1
    Make it `mp[find(i)]++;`, then you get [correct answer](https://godbolt.org/z/KfvqqP96M) at least for one particular test case. – Igor Tandetnik Jan 10 '22 at 15:32

0 Answers0