def parse(inFile):
return tuple(inFile.getInts() + [inFile.getInts()])
def solve((R,K,N,groups)):
i = 0
pos = 0
money = 0
if (K > sum(groups)):
K = sum(groups)
cache = [[-1,-1] for ij in xrange(N)]
while (i < R):
if (cache[pos][0] == -1):
cache[pos] = [i, money]
else:
[i2, money2] = cache[pos]
repeats = (R - i - 1) / (i - i2)
if (repeats >= 0):
i += repeats * (i - i2)
money += repeats * (money - money2)
cache = [[-1,-1] for ij in xrange(N)]
people = 0
while (people + groups[pos] <= K):
people += groups[pos]
pos += 1
if (pos == N):
pos = 0
money += people
i += 1
return money
if __name__ == "__main__":
from GCJ import GCJ
GCJ(parse, solve, "/Users/lpebody/gcj/2010_q/", "c").run()
ZGVmIHBhcnNlKGluRmlsZSk6CiAgICByZXR1cm4gdHVwbGUoaW5GaWxlLmdldEludHMoKSArIFtpbkZpbGUuZ2V0SW50cygpXSkKIApkZWYgc29sdmUoKFIsSyxOLGdyb3VwcykpOgogICAgaSA9IDAKICAgIHBvcyA9IDAKICAgIG1vbmV5ID0gMAogICAgaWYgKEsgPiBzdW0oZ3JvdXBzKSk6CiAgICAgICAgSyA9IHN1bShncm91cHMpCiAgICBjYWNoZSA9IFtbLTEsLTFdIGZvciBpaiBpbiB4cmFuZ2UoTildCiAgICB3aGlsZSAoaSA8IFIpOgogICAgICAgIGlmIChjYWNoZVtwb3NdWzBdID09IC0xKToKICAgICAgICAgICAgY2FjaGVbcG9zXSA9IFtpLCBtb25leV0KICAgICAgICBlbHNlOgogICAgICAgICAgICBbaTIsIG1vbmV5Ml0gPSBjYWNoZVtwb3NdCiAgICAgICAgICAgIHJlcGVhdHMgPSAoUiAtIGkgLSAxKSAvIChpIC0gaTIpCiAgICAgICAgICAgIGlmIChyZXBlYXRzID49IDApOgogICAgICAgICAgICAgICAgaSArPSByZXBlYXRzICogKGkgLSBpMikKICAgICAgICAgICAgICAgIG1vbmV5ICs9IHJlcGVhdHMgKiAobW9uZXkgLSBtb25leTIpCiAgICAgICAgICAgICAgICBjYWNoZSA9IFtbLTEsLTFdIGZvciBpaiBpbiB4cmFuZ2UoTildCiAgICAgICAgcGVvcGxlID0gMAogICAgICAgIHdoaWxlIChwZW9wbGUgKyBncm91cHNbcG9zXSA8PSBLKToKICAgICAgICAgICAgcGVvcGxlICs9IGdyb3Vwc1twb3NdCiAgICAgICAgICAgIHBvcyArPSAxCiAgICAgICAgICAgIGlmIChwb3MgPT0gTik6CiAgICAgICAgICAgICAgICBwb3MgPSAwCiAgICAgICAgbW9uZXkgKz0gcGVvcGxlCiAgICAgICAgaSArPSAxCiAgICByZXR1cm4gbW9uZXkKCmlmIF9fbmFtZV9fID09ICJfX21haW5fXyI6CiAgICBmcm9tIEdDSiBpbXBvcnQgR0NKCiAgICBHQ0oocGFyc2UsIHNvbHZlLCAiL1VzZXJzL2xwZWJvZHkvZ2NqLzIwMTBfcS8iLCAiYyIpLnJ1bigpCgogICAgICAgICAgICAK