The key to my solution was the recursive traversal (traverse_graph) of a directed graph. The representation of the graph is a dictionary of the monks as keys and a list of the following monks as values.
Because running on the large input file raised a runtime error of maximum recursion depth exceeded, I used a this little hack:
sys.setrecursionlimit(10000)
.UPDATE: Here are the solutions of the contestants.
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
''' | |
this is a solution of the EuroPython 2011 Problem D. Twibet | |
http://code.google.com/codejam/contest/dashboard?c=1277486#s=p3 | |
''' | |
def build_graph(input_list): | |
di = {} | |
for i in range(1, len(input_list)+1): | |
di[i] = [] | |
for monk, followed_monk in enumerate(input_list, start=1): | |
di[followed_monk].append(monk) | |
return di | |
def traverse_graph(graph, start, monks_today): | |
monks_today.add(start) | |
result = 1 | |
result += sum(map(lambda monk: traverse_graph(graph, monk, monks_today), \ | |
filter(lambda monk : monk not in monks_today, graph[start]))) | |
return result | |
def solve_case(case_no, line): | |
print "Case #%i:" % case_no | |
input_list = map(int, line.split()) | |
for monk in range(1, len(input_list)+1): | |
print traverse_graph(build_graph(input_list), monk, set()) | |
def main(): | |
import sys | |
sys.setrecursionlimit(10000) | |
lines = sys.stdin.readlines() | |
for case_no, line in enumerate(lines[2::2], start=1): | |
solve_case(case_no, line.strip()) | |
main() |