< Back to forum

some test cases is accepted but some showing wrong. problem link https://www.codechef.com/problems/COLCHEF below my code

#include<bits/stdc++.h>
using namespace std;
const int MAX=100004;
int p[MAX],rank1[MAX]={0};
void MAKESET(int n){
   for(int i=1;i<=n;i++)
    p[i]=i;
}
int FIND(int x){
    if(p[x]!=x)
        p[x]=FIND(p[x]);
    return p[x];
}
void union1(int x,int y){
   int rx=FIND(x);
   int ry=FIND(y);
   if(rx==ry)
    return ;
    if(rank1[ry]>rank1[rx]){
        p[rx]=ry;
        }
   else if(rank1[rx]>rank1[ry]){
         p[ry]=rx;
         }
     else{
        p[ry]=rx;
        rank1[rx]+=1;
     }}
main()
{
    int n,q,x,a,b,i,k=0;
    cin>>n;
    MAKESET(n);
    cin>>q;
    while(q--){
      cin>>x>>a>>b;
      if(x==0)
       union1(a,b);
      else{
            if(p[a]==p[b])
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;}
      }
    }

Asked by: Deepak_kumar_Shaw on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Enter your comment details below:




1 Answer(s)

avatar

to find the parent of any element you need to use the FIND function. Using the value stored in the parent array will not give the true parent when height is greater then 1.
so use
 

            if(FIND(p[a]) == FIND(p[b]))
            cout<<"YES"<<endl;

 

Shubham_Kumar_Gupta last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.