-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathtotal_pairs_chosen.cpp
90 lines (82 loc) · 2.04 KB
/
total_pairs_chosen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*Problem Statement:
The member states of the UN are planning to send people to the moon.
They want them to be from different countries. You will be given a list of pairs of astronaut ID's.
Each pair is made of astronauts from the same country.
Determine how many pairs of astronauts from different countries they can choose from. */
#include<bits/stdc++.h>
using namespace std;
list<int> *ad;
int *visited;
int vertices;
void DFS(int u)
{
visited[u] = 1;
vertices++;
list<int>::iterator it;
for(it=ad[u].begin();it!=ad[u].end();it++)
{
//If the node is not visited
if(visited[*it] == 0)
{
visited[*it] = 1;
DFS(*it);
}
}
}
int main()
{
int no_astronauts,pairs,u,v,numComponents=0,all_vertices=0,temp=2,count=0;
int eachC[1000];
cout << "Enter total number of astronauts and the total no of pairs: "<<endl;
cin >> no_astronauts >> pairs;
if(no_astronauts == 1)
{
cout <<"0"<<endl;
return 0;
}
ad = new list<int>[no_astronauts];
list<int>::iterator it;
cout<<"Enter id and nationality: "<<endl;
for(int i=0;i<pairs;i++)
{
cin >> u >> v;
ad[u].push_back(v);
ad[v].push_back(u);
}
visited = new int[no_astronauts];
for(int i=0;i<no_astronauts;i++)
{
visited[i] = 0;
}
for(int i=0;i<no_astronauts;i++)
{
if(visited[i] == 0)
{
vertices = 0;
DFS(i);
eachC[numComponents] = vertices;
numComponents++;
}
}
int totalWays = no_astronauts*(no_astronauts-1) / 2;
int sameWays = 0;
for(int i=0;i<numComponents;i++)
{
sameWays = sameWays + (eachC[i]*(eachC[i]-1) / 2);
}
cout << "Total chosen pairs: " << (totalWays - sameWays) << endl;
return 0;
}
/*Example:-
Input:-
Enter total number of astronauts and the total no of pairs:
5 3
Enter id and nationality:
0 1
2 3
0 4
Output:-
Total chosen pairs: 6
Time Complexity: O(n)
Space Complexity: O(n)
*/