We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<list>#include<vector>#include<stdio.h>#include<iterator>#include<cmath>#define MAX 100000usingnamespacestd;list<int>*ad;int*visited;intvertices;voidDFS(intu){visited[u]=1;vertices++;list<int>::iteratorit;for(it=ad[u].begin();it!=ad[u].end();it++){if(visited[*it]==0){visited[*it]=1;DFS(*it);}}}intmain(){inti,m,u,v,numComponents=0,allv=0,temp=2,count=0;longlongintn;inteachC[MAX];cin>>n>>m;if(n==1){cout<<"0\n";return0;}ad=newlist<int>[n];list<int>::iteratorit;for(i=0;i<m;i++){cin>>u>>v;ad[u].push_back(v);ad[v].push_back(u);}visited=newint[n];for(i=0;i<n;i++){visited[i]=0;}for(i=0;i<n;i++){if(visited[i]==0){vertices=0;DFS(i);eachC[numComponents]=vertices;numComponents++;}}longlonginttotalWays=n*(n-1)/2;longlongintsameWays=0;for(i=0;i<numComponents;i++){sameWays=sameWays+(eachC[i]*(eachC[i]-1)/2);}cout<<(totalWays-sameWays)<<endl;return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
Easy C++ Solution: