There are N people in the town (N>=2), and function Know(i,j) return true if i knows j and false otherwise. The knowing relationship is not symmetric. Know(i,j)==true cannot guarantee Know(j,i)==true. Find those people: everyone knows him but he knows nobody else.
int find()
{
int i =0;
int j =1;
int next =2;
//first find the gay
while(next <= N) //if still have someone not remove
{
if (Know(i, j)) //if i know j, i is not we want
{
i = next;
}
else
{
j = next;
}
++next; //consider the next one
}
int cand = i; //candidate
if (i == N)
{
cand = j;
}
//check if the cadidate is the one we want to find
for (int k =0; k < N; ++k)
{
if (k == cond)
{
continue;
}
if (Know(cand, k) ||!Know(k, cand)) //if candidate know k or k not know candidate
{
return-1;
}
}
return cand;
}
{
int i =0;
int j =1;
int next =2;
//first find the gay
while(next <= N) //if still have someone not remove
{
if (Know(i, j)) //if i know j, i is not we want
{
i = next;
}
else
{
j = next;
}
++next; //consider the next one
}
int cand = i; //candidate
if (i == N)
{
cand = j;
}
//check if the cadidate is the one we want to find
for (int k =0; k < N; ++k)
{
if (k == cond)
{
continue;
}
if (Know(cand, k) ||!Know(k, cand)) //if candidate know k or k not know candidate
{
return-1;
}
}
return cand;
}