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.
The 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.
For 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).
题目地址:https://codeforces.com/contest/1328/problem/B
题解:通过循环找到第k条的第1b和第二个b。第一个b,枚举i=1,2,3,。。。直到i*(n-1)/2>=k且不断执行k = k - i,第一个b在n-i的位置上,第二个b在n-k+1上。
AC代码:
#include <stdio.h> #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <map> #include<math.h> #include<stack> #include <queue> using namespace std; #define maxn 10010 #define Minf -1e9 typedef long long ll; #define INF 1e9 int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k;int i; for (i = 1; ; 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; } }

浙公网安备 33010602011771号