Welcome to code jam, the third question of Qualification Round 2009. The general meaning of the question is that, given a string, it is required to find the number of welcome to code jam and give the last four digits. If these 19 characters appear in order, they can be counted as one time, regardless of whether they are separated by other characters.
In Contest Analysis, dynamic planning is used. After thinking for a while, I did not think about the solution and then I directly looked at the answer...
The idea of dynamic planning is that cnt [I, j] indicates the number of first j characters of welcome to code jam in the first I characters of a given string, when processing I + 1 characters,
If the I + 1 character is the corresponding j character, then cnt [I + 1] [j] = cnt [I] [j] + cnt [I] [J-1]; otherwise, cnt [I + 1] [j] = cnt [I] [j].
The dynamic planning table is as follows,
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
The Code is as follows:
#/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()
For the final result, the last four digits must be displayed. The printing format should be set to 4 and the filling is set to 0, which is similar to C/C ++, but it cannot be found. It can only be written in that way.
If you know anything, please tell me. Thank you!