google code jam exercise——welcome to code jam
Welcome to code jam,Qualification Round 2009的第三道题。题目的大概意思是,给定一个字符串,要求找出里面welcome to code jam的次数,给出最后四位数字。只要这19个字符按顺序出现了,就可以算作一次,不管是否被其它字符隔开。
在Contest Analysis中,给的方法是动态规划。在思考了一小会没有想到解法之后又直接看答案了。。。
动态规划的思想是,cnt[i,j]表示在给定的字符串的前i个字符中,出现welcome to code jam的前j个字符的个数,那么处理i+1个字符时,
如果第i+1个字符是对应的第j个字符,那么cnt[i+1][j]=cnt[i][j]+cnt[i][j-1];否则cnt[i+1][j]=cnt[i][j]。
动态规划表格表示如下,
j j+1
i $a $b
i+1 if case[i+1]==pattern[j+1] $c=$a+$b
if case[i+1]!=pattern[j+1] $c=$b
代码如下:
#/usr/bin/python
#encoding:UTF-8
#Filename:Welcome.py
import sys
def solveCnt(s,case):
m = len(s)
n = len(case)
cnt = [[0 for j in range(m+1)] for i in range(n+1)]
j = 1
for i in range(1,n+1):
if case[i-1]==s[j-1]:
cnt[i][j] = cnt[i-1][j] + 1
if cnt[i][j]>=10000:
cnt[i][j] = cnt[i][j]%10000
else:
cnt[i][j] = cnt[i-1][j]
for i in range(1,n+1):
for j in range(2,m+1):
if case[i-1]==s[j-1]:
cnt[i][j] = cnt[i-1][j]+cnt[i-1][j-1]
if cnt[i][j]>=10000:
cnt[i][j] = cnt[i][j]%10000
else:
cnt[i][j] = cnt[i-1][j]
return cnt[n][m]
inname = "input.txt"
outname = "output.txt"
if len(sys.argv)>1:
inname = sys.argv[1]
outname = inname.rstrip(".in")
outname = outname + ".out"
fin = open(inname,"r")
fout = open(outname,"w")
s = "welcome to code jam"
testCaseNum = int(fin.readline().rstrip("\n"))
for caseNum in range(testCaseNum):
line = fin.readline()
line = line.rstrip("\n")
answer = "Case #%d: " %(caseNum+1)
an = solveCnt(s,line)
if an<10:
answer = answer + "000%d" %(an)
elif an<100:
answer = answer + "00%d" %(an)
elif an<1000:
answer = answer + "0%d" %(an)
else:
answer = answer + str(an)
answer = answer + "\n"
fout.write(answer)
fin.close()
fout.close()
对于最后结果,要求显示最后四位数字,应该有打印格式选定位宽为4,设定填充为0的方法的,与C/C++类似的,不过没有找到,只能那样写了。
如果有知道的,希望能告诉我,谢谢!