B. K-th Beautiful String
For the given integer nn (n>2n>2) let's write down all the strings of length nn which contain n−2n−2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order.
Recall that the string ss of length nn is lexicographically less than string tt of length nn, if there exists such ii (1≤i≤n1≤i≤n), that si<tisi<ti, and for any jj (1≤j<i1≤j<i) sj=tjsj=tj. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.
For example, if n=5n=5 the strings are (the order does matter):
- aaabb
- aabab
- aabba
- abaab
- ababa
- abbaa
- baaab
- baaba
- babaa
- bbaaa
It is easy to show that such a list of strings will contain exactly n⋅(n−1)2n⋅(n−1)2 strings.
You are given nn (n>2n>2) and kk (1≤k≤n⋅(n−1)21≤k≤n⋅(n−1)2). Print the kk-th string from the list.
InputThe input contains one or more test cases.
The first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then tt test cases follow.
Each test case is written on the the separate line containing two integers nn and kk (3≤n≤105,1≤k≤min(2⋅109,n⋅(n−1)2)3≤n≤105,1≤k≤min(2⋅109,n⋅(n−1)2).
The sum of values nn over all test cases in the test doesn't exceed 105105.
OutputFor each test case print the kk-th string from the list of all described above strings of length nn. Strings in the list are sorted lexicographically (alphabetically).
好像可以全排列做,不过我的做法不一样,我是通过找规律,第一个b在倒数第二位有1个,倒数第三位2个,倒数第四位三个,第二个b的位置就是k-1-2-3-...剩下的数字倒着数
那么普通的循环就解决了
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> using namespace std; typedef long long ll; #define INF 99999999 #define MAXN 100 int m, n, t, k; int main() { cin >> t; while (t--) { cin >> n >> k; int i = 0; for (i = 1; i < n; i++) { if (k <= i) { break; } k -= i; } i = n - i; k = n - k+1; for (int j = 1; j <= n; j++) { if (j == i || j == k) { cout << "b"; } else { cout << "a"; } } cout << endl; } return 0; }

浙公网安备 33010602011771号