from random import sample
def reader(inFile):
N = inFile.getInt()
prerequisites = inFile.getInts()
letters = inFile.readline()
M = inFile.getInt()
coolWords = inFile.getWords()
return (N,prerequisites,letters,coolWords)
def solver((N,prerequisites,letters,words)):
# For any course, find out which courses directly depend on it.
# Also get a list of basic courses.
directDependencies = {i:[] for i in xrange(1,N+1)}
basics = []
for i in xrange(1,N+1):
if prerequisites[i-1] == 0:
basics.append(i)
else:
directDependencies[prerequisites[i-1]].append(i)
# Get the number of courses which directly or indirectly depend on each course.
numDependents = {}
def getNumDependents(i):
tot = 1
for j in directDependencies[i]:
tot += getNumDependents(j)
numDependents[i] = tot
return tot
for i in basics:
getNumDependents(i)
# Sample from uniform random distribution of orderings
def placeDependentsAndReturnRemaining(sampleSoFar, i, available):
# The nodes that are used by i and its (direct or indirect) dependencies are
# equally likely to be any set of the same size, given that there are no
# interdependencies with other nodes still to place
dependencyLocations = sample(available, numDependents[i])
# i must be the first of these to be placed
w = min(dependencyLocations)
others = [z for z in dependencyLocations if z != w]
sampleSoFar[w] = letters[i-1]
for j in directDependencies[i]:
others = placeDependentsAndReturnRemaining(sampleSoFar, j, others)
dependencyLocations = set(dependencyLocations)
return [k for k in available if k not in dependencyLocations]
def randomSample():
sampleSoFar = ["" for i in xrange(N)]
remaining = range(N)
for j in basics:
remaining = placeDependentsAndReturnRemaining(sampleSoFar, j, remaining)
return "".join(sampleSoFar)
# If you a coin flip with probability p N times, the number of heads has
# mean Np and standard deviation sqrt(Np(1-p))
# Thus, the estimated probability will be p with standard deviation sqrt(p(1-p)/N)
# If we sample 10000 times, the standard deviation is at most 0.005, so being 0.03 wrong
# is 6 standard deviations out, and we would rarely expect to see such an error in our
# 500 (5 words x 100 test cases) tests.
counts = [0 for i in words]
sampleSize = 10000
for i in xrange(sampleSize):
w = randomSample()
for p in xrange(len(words)):
if words[p] in w:
counts[p] += 1
return " ".join(str(float(count)/sampleSize) for count in counts)
if __name__ == "__main__":
from GCJ import GCJ
GCJ(reader, solver, "/Users/luke/gcj/2016/3/", "b").run()