File tree 1 file changed +69
-0
lines changed
The Celebrity Problem - GFG
1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ // { Driver Code Starts
2
+ // Initial template for C++
3
+
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ // } Driver Code Ends
8
+ // User function template for C++
9
+
10
+ class Solution
11
+ {
12
+ public:
13
+ // Function to find if there is a celebrity in the party or not.
14
+ int celebrity (vector<vector<int > >& arr, int people)
15
+ {
16
+ // code here
17
+ stack<int > s;
18
+ for (int i=0 ;i<people;i++){
19
+ s.push (i);
20
+ }
21
+ while (s.size ()>1 ){
22
+ int p1 = s.top ();
23
+ s.pop ();
24
+ int p2 = s.top ();
25
+ s.pop ();
26
+ if (arr[p1][p2]==1 && arr[p2][p1]==0 ){
27
+ s.push (p2);
28
+ }
29
+ else if (arr[p1][p2]==0 && arr[p2][p1]==1 ){
30
+ s.push (p1);
31
+ }
32
+ }
33
+ if (s.empty ()){
34
+ return -1 ;
35
+ }
36
+ int expected = s.top ();
37
+ for (int i=0 ;i<people;i++){
38
+ if (i!=expected && (arr[expected][i]!=0 || arr[i][expected]!=1 )){
39
+ return -1 ;
40
+ }
41
+ }
42
+ return expected;
43
+ }
44
+ };
45
+
46
+ // { Driver Code Starts.
47
+
48
+ int main ()
49
+ {
50
+ int t;
51
+ cin>>t;
52
+ while (t--)
53
+ {
54
+ int n;
55
+ cin>>n;
56
+ vector<vector<int > > M ( n , vector<int > (n, 0 ));
57
+ for (int i=0 ;i<n;i++)
58
+ {
59
+ for (int j=0 ;j<n;j++)
60
+ {
61
+ cin>>M[i][j];
62
+ }
63
+ }
64
+ Solution ob;
65
+ cout<<ob.celebrity (M,n)<<endl;
66
+
67
+ }
68
+ }
69
+ // } Driver Code Ends
You can’t perform that action at this time.
0 commit comments