forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
140.cpp
62 lines (52 loc) · 1.05 KB
/
140.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
// C++ program to find celebrity
#include <bits/stdc++.h>
#include <list>
using namespace std;
// Max # of persons in the party
#define N 8
// Person with 2 is celebrity
bool MATRIX[N][N] = {{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 0, 0},
{0, 0, 1, 0}};
bool knows(int a, int b)
{
return MATRIX[a][b];
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n)
{
//the graph needs not be constructed
//as the edges can be found by
//using knows function
//degree array;
int indegree[n]={0},outdegree[n]={0};
//query for all edges
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
int x = knows(i,j);
//set the degrees
outdegree[i]+=x;
indegree[j]+=x;
}
}
//find a person with indegree n-1
//and out degree 0
for(int i=0; i<n; i++)
if(indegree[i] == n-1 && outdegree[i] == 0)
return i;
return -1;
}
// Driver code
int main()
{
int n = 4;
int id = findCelebrity(n);
id == -1 ? cout << "No celebrity" :
cout << "Celebrity ID " << id;
return 0;
}