On hackerrank, 1 test case in not passing .
This is the test case:
Input :
100000 2
1 2
3 4
Output:
4999949998
Check out.
On hackerrank, 1 test case in not passing .
This is the test case:
Input :
100000 2
1 2
3 4
Output:
4999949998
Check out.
#include <bits/stdc++.h>
using namespace std;
class Graph{
long int V;
list<pair<int,int>> l;
public:
Graph(long int V){
this->V = V;
}
void addEdge(int u, int v){
l.push_back(make_pair(u,v));
}
int find(int i, int parent[]) {
if(parent[i]==-1){
return i;
}
return parent[i] = find(parent[i],parent);
}
void unionSet(int x, int y, int parent[], int rank[]) {
int s1 = find(x,parent);
int s2 = find(y,parent);
if(s1!=s2){
if(rank[s1]<rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}
else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
int pairing(){
int *parent = new int[V];
int *rank = new int[V];
for(int i=0;i<V;i++){
parent[i] = -1;
rank[i] = 1;
}
for(auto edge:l){
int i = edge.first;
int j = edge.second;
int s1 = find(i,parent);
int s2 = find(j,parent);
unionSet(s1,s2,parent,rank);
}
long long int ans=0;
for(long int i=0;i<V;i++){
ans += V - rank[find(i,parent)];
}
return ans/2;
}
};
int main(){
long int n,p;
cin>>n>>p;
Graph g(n);
while(p--) {
int u,v;
cin>>u>>v;
g.addEdge(u,v);
}
cout<<g.pairing()<<endl;
return 0;
}
Yes, getting correct output for this.