Created
June 13, 2017 06:00
-
-
Save yokolet/8b9e766261890b78e849d162efcf82a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class FindTheCelebrity { | |
static int N = 7; | |
static Map<Integer, List<Integer>> relation = new HashMap(); | |
static { | |
relation.put(0, Arrays.asList(1)); | |
relation.put(1, new ArrayList()); // celebrity | |
relation.put(2, Arrays.asList(1)); | |
relation.put(3, Arrays.asList(1, 2)); | |
relation.put(4, Arrays.asList(1)); | |
relation.put(5, Arrays.asList(1)); | |
relation.put(6, Arrays.asList(1, 5)); | |
} | |
static boolean knows(int a, int b) { | |
return relation.get(a).contains(b); | |
} | |
static int findCelebrity() { | |
Stack<Integer> stack = new Stack(); | |
for (int i = 0; i < N; i++) { | |
stack.push(i); | |
} | |
// elimination | |
while (stack.size() > 1) { | |
int a = stack.pop(); | |
int b = stack.pop(); | |
if (knows(a, b)) { | |
// a knows b | |
// b is a potential celeb | |
// make b back to stack | |
stack.push(b); | |
} else { | |
// a doesn't knows b | |
// a is a potential celeb | |
// make a back to stack | |
stack.push(a); | |
} | |
} | |
int c = stack.pop(); | |
// verification | |
for (int i = 0; i < N; i++) { | |
if ((i != c) && (knows(c, i) || !knows(i, c))) { | |
return -1; | |
} | |
} | |
return c; | |
} | |
public static void main(String[] args) { | |
System.out.println(findCelebrity()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment