-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
total_more_child_vertices_than_parent.cpp
146 lines (128 loc) · 3.04 KB
/
total_more_child_vertices_than_parent.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*Problem Statement:
You are given a graph with N vertices and M edges.
Master parent is the vertex which has no parent but may have 0 or more children.
In any connected component of the graph,
vertex with the lowest value in that component serves as the master parent.
Count the total no of vertices which have more children than its parent.
The graph has no cycles or self loops. */
#include <bits/stdc++.h>
using namespace std;
class graph
{
public:
int V;
list<int> *adjList;
list<int> *realList;
graph(int V)
{
this->V = V;
adjList = new list < int>[V];
realList = new list < int>[V];
}
void addEdge(int u, int v)
{
adjList[u].push_back(v);
}
void Make_edges()
{
set<int> s;
for (int i = 0; i < V; i++)
{
s.insert(i);
}
while (s.empty() == false)
{
bool visited[V];
for (int i = 0; i < V; i++)
{
visited[i] = false;
}
set<int>::iterator it = s.begin();
queue<int> q;
q.push(*it);
while (q.empty() == false)
{
int x = q.front();
q.pop();
visited[x] = true;
s.erase(x);
int size = adjList[x].size();
for (int i = 0; i < size; i++)
{
int k = adjList[x].front();
adjList[x].pop_front();
if (visited[k] == false)
{
q.push(k);
realList[x].push_back(k);
}
}
}
}
}
int total_vertices()
{
int child[V];
for (int i = 0; i < V; i++)
{
child[i] = 0;
}
int cnt = 0;
for (int i = 0; i < V; i++)
{
child[i] = realList[i].size();
}
for (int i = 0; i < V; i++)
{
int size = realList[i].size();
for (int k = 0; k < size; k++)
{
if (child[realList[i].front()] > child[i] && child[i] != 0)
{
cnt++;
}
realList[i].pop_front();
}
}
return cnt;
}
};
int main()
{
int n;
cout << "Enter the total vertices: " << endl;
cin >> n;
graph g(n);
int m;
cout << "Enter the total edges: " << endl;
cin >> m;
int u;
int v;
cout << "Enter edges: " << endl;
while (m--)
{
cin >> u >> v;
u--;
v--;
g.addEdge(u, v);
g.addEdge(v, u);
}
g.Make_edges();
cout << "Total vertices with more than total children than the parents: " << g.total_vertices();
return 0;
}
/*Example:-
Input:-
Enter the total vertices:
4
Enter the total edges:
3
Enter edges:
1 2
2 3
2 4
Output:-
Total vertices with no more than total children than the parents: 1
Time Complexity: O(n)
Space Complexity: O(n)
*/