Help with INOI graph problem

How can I solve this problem SEQUENCE LAND from INOI 13? CodeChef: Practical coding for everyone

My initial approach was to check every possible pair of relatives and then do a dfs on the king and find the size of the graph. But to check for relatives it took me O(n^4) time - 6ZhqNB - Online C++0x Compiler & Debugging Tool - Ideone.com . To speed it up I tried using binary search O(n^3 logn) oV2tHw - Online C++0x Compiler & Debugging Tool - Ideone.com but that doesn’t seem to work for some reason can anybody find out the problem in my binary search code or suggest a better way to solve this problem?

think in terms of bfs algo
where prez is the root

specifically those queue we see in bfs algo
that has something to do with the problem here