https://hack.codingblocks.com/contests/c/471/1171
https://ide.codingblocks.com/#/s/21616
Wrong answer in PAIRING problem
I am not able to understand your logic. Have you worked on edges??
My approach was to find number of nodes in different connected components using dfs and use that to get the answer. Picking two nodes of different component will be a possible way.
Here’s my code for help.
#include <bits/stdc++.h>
using namespace std;
int dfs(vector *arr,bool *mark,int node)
{
if(mark[node])
return 0;
mark[node]=1;
int ans=1;
for(auto it=arr[node].begin();it!=arr[node].end();it++)
ans+=dfs(arr,mark,*it);
return ans;
}
int main() {
// your code goes here
int N,M;
cin>>N>>M;
vector arr[N];
for(int i=0;i<M;i++)
{
int x,y;
cin>>x>>y;
arr[x].push_back(y);
arr[y].push_back(x);
}
vector component;
bool mark[N];
for(int i=0;i<N;i++)
mark[i]=0;
for(int i=0;i<N;i++)
if(!mark[i])
component.push_back(dfs(arr,mark,i));
long long ans=0;
for(int i=0;i<component.size();i++)
for(int j=i+1;j<component.size();j++)
ans+=component[i]*component[j];
cout<<ans;
return 0;
}