Find the Celebrity in C++

C++Server Side ProgrammingProgramming

Suppose we have n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. We can say a person x is a celebrity when all the other n - 1 people know x but x does not know any of them. Here we have to find who the celebrity is or verify that there is not one.

We are allowed to ask only one question to person ‘A’, that "Hi, A. Do you know B?" to get information of whether A knows B or not. We have to ask minimum number of questions tofind out the celebrity. There is a list of lists as input called graph, the graph[i,j] = 1 when ith person knows jth person, otherwise 0.

So, if the input is like graph = [[1,1,0],[0,1,0],[1,1,1]],

then the output will be 1, as the celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.

To solve this, we will follow these steps −

  • Define a function knows(), this will take a, b,

  • return true when graph[a, b] is true

  • From the main method do the following −

  • Define one stack st

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • insert i into st

  • while size of st > 1, do −

    • x := top element of st

    • delete element from st

    • y := top element of st

    • delete element from st

    • if knows(x, y) is true then, then −

      • insert y into st

    • Otherwise

      • insert x into st

  • x := top element of st

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • if i is same as x, then −

      • Ignore following part, skip to the next iteration

    • if knows(x, i) is true or knows(i, x) is false, then −

      • return -1

  • return x

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   vector<vector<int<> graph;
public:
   Solution(vector<vector<int<> &graph){
      this->graph = graph;
   }
   bool knows(int a, int b){
      return graph[a][b];
   }
   int findCelebrity(int n) {
      stack<int< st;
      for (int i = 0; i < n; i++) {
         st.push(i);
      }
      while (st.size() > 1) {
         int x = st.top();
         st.pop();
         int y = st.top();
         st.pop();
         if (knows(x, y)) {
            st.push(y);
         }
         else {
            st.push(x);
         }
      }
      int x = st.top();
      for (int i = 0; i < n; i++) {
         if (i == x)
            continue;
         if (knows(x, i) || !knows(i, x)) {
            return -1;
         }
      }
      return x;
   }
};
main(){
   vector<vector<int<> v = {{1,1,0},{0,1,0},{1,1,1}};
   Solution ob(v);
   cout << (ob.findCelebrity(3));
}

Input

{{1,1,0},{0,1,0},{1,1,1}}
3

Output

1
raja
Updated on 18-Nov-2020 11:46:42

Advertisements