-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_TheCelebrityProblem.cpp
96 lines (82 loc) · 1.94 KB
/
GFG_TheCelebrityProblem.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
/*
https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1#
The Celebrity Problem
*/
// { Driver Code Starts
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution
{
public:
//Function to find if there is a celebrity in the party or not.
int celebrity_(vector<vector<int> >& M, int n)
{
vector<int> indeg(n,0);
vector<int> outdeg(n,0);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(M[i][j])
{
outdeg[i]++;
indeg[j]++;
}
}
}
for(int i=0; i<n; i++)
{
if(indeg[i]==n-1 && outdeg[i]==0)
return i;
}
return -1;
}
int celebrity(vector<vector<int> >& M, int n)
{
stack<int> st;
int a,b, ans;
for(int i=0; i<n; i++)
st.push(i);
while(st.size()>1)
{
a = st.top(); st.pop();
b = st.top(); st.pop();
if(M[a][b]) st.push(b); // a to bilkul nhi he
else st.push(a); // b nhi ho skta
}
ans = st.top();
int cntzero=0, cntone=0;
for(int c=0; c<n; c++)
{
if(M[ans][c]==0) cntzero++;
if(M[c][ans]==1) cntone++;
}
if(cntone == n-1 and cntzero == n) return ans;
else return -1;
}//end
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<vector<int> > M( n , vector<int> (n, 0));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>M[i][j];
}
}
Solution ob;
cout<<ob.celebrity(M,n)<<endl;
}
}
// } Driver Code Ends