Problem Statement
Among the strings of length A+B containing A occurrences of a and B occurrences of b, find the string that comes K-th in the lexicographical order.
Sample Input 1
2 2 4
Sample Output 1
baab
Sample Input 2
30 30 118264581564861424
Sample Output 2
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
思维题~
打表很容易发现
A
A
A 个
a
a
a,
B
B
B 个
b
b
b 的排列情况就是
C
A
+
B
A
C_{A+B}^A
CA+BA,那么我们可以从前往后依次填字母,将
K
K
K 和此时的排列个数
n
u
m
num
num 比较即可:
- K > n u m K>num K>num,证明是较后的排列,填入字母 b b b, K = K − n u m K=K-num K=K−num
- K ≤ n u m K\leq num K≤num,若 a a a 有剩余先填 a a a, a a a 填完了再填 b b b
因为涉及到大数,我直接用的 p y t h o n python python,AC代码如下:
def f(n, m):
x, y = 1, 1
for i in range(1, m + 1):
x *= (n - i + 1)
y *= i
return x // y
a, b, c = map(int, input().split())
n = a + b
l = a + b
ans = ''
for i in range(0, l):
s = f(n - 1, a - 1)
if c > s:
c -= s
ans += 'b'
b -= 1
else:
if a:
ans += 'a'
a -= 1
elif b:
ans += 'b'
b -= 1
n -= 1
print(ans)