027 school recruit Zhenti practice Xiao Yi dictionary (NetEase)

Xiao Yi dictionary

Title Description
Xiao Yi learned about string theory in school, he completed a project based on this dictionary.
Xiao Yi very strange in the dictionary, each word in the dictionary contains the n 'a' and m 'z', and all words are arranged in lexicographic order.
Xiao Yi now want you to help him find out what the k-word yes.

Description Input :
Input includes a row of three integers n, m, k (1 < = n, m <= 100, 1 <= k <= 109), separated by spaces.

Description Output :
output string k-th dictionary, if no solution, output -1.

 1 def Cnm(a, b):
 2     ans =1
 3     for i in range(a+1, a + b +1):
 4         ans *=i
 5     for i in range(1, b +1):
 6         ans //=i
 7     return ans
 8   
 9 n, m, k =map(int, input().strip().split())
10 if Cnm(n, m) < k:
11     print(-1)
12 else:
13     ans =""
14     while n > 0 and m > 0:
15         temp =Cnm(n -1, m)
16         if temp <k:
17             k-=temp
18             ans +="z"
19             m -=1
20         else:
21             ans +="a"
22             n -=1
23     ans +="a"*n
24     ans +="z"*m
25     print(ans)

Is the subject of math class, algorithm idea is to permutations and combinations, but not exhaustive of all permutations.

Reference: https://www.nowcoder.com/profile/1424034/codeBookDetail?submissionId=31703838

 

Guess you like

Origin www.cnblogs.com/asenyang/p/11235652.html