For the given integer n (n>2) let’s write down all the strings of length n which contain n−2 letters ‘a’ and two letters ‘b’ in lexicographical (alphabetical) order.
Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1≤i≤n), that si<ti, and for any j (1≤j<i) sj=tj. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.
For example, if n=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)2 strings.
You are given n (n>2) and k (1≤k≤n⋅(n−1)2). Print the k-th string from the list.
Input
The input contains one or more test cases.
The first line contains one integer t (1≤t≤104) — the number of test cases in the test. Then t test cases follow.
Each test case is written on the the separate line containing two integers n and k (3≤n≤105,1≤k≤min(2⋅109,n⋅(n−1)2).
The sum of values n over all test cases in the test doesn’t exceed 105.
Output
For each test case print the k-th string from the list of all described above strings of length n. Strings in the list are sorted lexicographically (alphabetically).
Example
Input
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
Output
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
题意:
一串长度为n的字符串由n-2个a和2个b组成,根据字典序排列出每一种排列情况,输入长度n和序列号k,输出第k组序列的字符串排列情况。
和
题解:
先预处理根据倒数第二个b的位置做前缀和记录其在每一个位置的情况和。然后遍历找到b所在位置即可。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<map>
#include<vector>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<set>
#include<cctype>
#include<string>
#include<stdexcept>
#include<fstream>
#define mem(a,b) memset(a,b,sizeof(a))
#define debug() puts("what the fuck!")
#define debug(a) cout<<#a<<"="<<a<<endl;
#define speed {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); };
#define ll long long
#define mod 998244353
using namespace std;
const double PI = acos(-1.0);
const int maxn = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const double esp_0 = 1e-6;
ll gcd(ll x, ll y) {
return y ? gcd(y, x % y) : x;
}
ll lcm(ll x, ll y) {
return x * y / gcd(x, y);
}
ll extends_gcd(ll a, ll b, ll& x, ll& y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
ll gcdd=extends_gcd(b, a % b, x, y);
ll temp = x;
x = y;
y = temp - (a / b) * y;
return gcdd;
}
int pos[maxn], sum[maxn];
int main(){
speed;
mem(pos, 0);
mem(sum, 0);
for (int i = 2; i <= maxn - 1; i++)pos[i] = pos[i - 1] + 1, sum[i] = sum[i - 1] + pos[i];
//for (int i = 1; i <= maxn - 1; ++i) {
// cout << i << ": " << pos[i] << " " << sum[i] << endl;
//}
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
int step = 0;
for (int i = 1; i <= n; ++i) {
if (k <= sum[i]) {
step = i;
break;
}
}
k -= sum[step - 1];
for (int i = 0; i < n; ++i) {
if (i == n - step || i == n - k)cout << 'b';
else cout << 'a';
}
cout << endl;
}
return 0;
}