Graph problem based on disjoint-set union

Here is the link of question:

Here is my code :

#include <bits/stdc++.h>
using namespace std;

int find(int x,vector<int>& parents)
{
    if(parents[x] == x)
    {
        return x;
    }
    int u = find(parents[x],parents);
    parents[x] = u;
    return u;
}

void unite(int x,int y,vector<int>& rank,vector<int>& parents)
{
    int p1 = find(x,parents);
    int p2 = find(y,parents);
    
    if(rank[p1] >= rank[p2])
    {
        rank[p1]++;
        rank[p1] =-1;
        parents[p2] = p1; 
    }
    else
    {
        rank[p2]++;
        rank[p1] = -1;
        parents[p1] = p2;
    }
}

int main() {
	// your code goes here
	int t;
	cin>>t;
	while(t--)
	{
	  int n;
	cin>>n;
	int m;
	cin>>m;
	vector<int>parents(n+1);
	vector<int>rank(n+1);
	for(int i=1;i<=n;i++)
	{
	    parents[i] = i;
	    rank[i] = 1;
	}
	while(m--)
	{
	    int x,y;
	    cin>>x>>y;
	    int p1 = find(x,parents);
	    int p2 = find(y,parents);
	    if(p1!=p2)
	    {
	        unite(x,y,rank,parents);
	    }
	}
	int ans1=0,ans2=1;
	for(int i=1;i<=n;i++)
	{
	    if(rank[i]>0)
	    {
	        ans1++;
	        ans2 = ans2*rank[i];
	    }
	}
	parents.clear();
	rank.clear();
	cout<<ans1<<" "<<ans2<<endl;    
	}
	return 0;
}

It is giving me Runtime(SIGABART) error ,Please help.

https://www.codechef.com/viewsolution/39027781

See my solution earlier i did with dfs and now since u asked did it with DSU.
Check my solution once if u dont understand where u r going wrong do tell

format your code .

u also forgot to use MOD 10^9+7 :slight_smile:

Thank u @kanisht09 for your help but please explain what does this line of code does?
par[x] += par[y];

Done :slight_smile:

see i have learnt DSU from coden-code youtube channel best lectures.
So i did that step to keep the length of connected component , that means the root element will keep the length of connected component of its graph. If u print the par[ ] array the negative numbers is the length of the connected component of node i ,
say p[i]=-5 that means node i is the parent and it has 5 nodes connected to it including itself . I hope u understood if u dont do watch from Coden Code u will definitely get it . :slight_smile:

Got it . Thanks :slight_smile:

1 Like

cool