Day 43 B. K-th Beautiful String

2023-05-16

Problem
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≤10^4) — 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≤10^5,1≤k≤min(2⋅10 ^9,n⋅(n−1)/2).

The sum of values n over all test cases in the test doesn’t exceed 10^5.

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 按照字典序排序直到两个b在最前面 求第x个字符串
//这其实是一道数学题

#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<stdio.h>
#include<limits.h>
#include<cmath>
#include<set>
#include<map>
#define ll long long
using namespace std;
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        ll n, k;
        cin >> n >> k;
        k = n * (n - 1) / 2 - k;
        string s(n, 'a');
        for (int i = 0; i < n; i++)
        {
            if (k < n - 1 - i)
            {
                s[i] = s[i + k + 1] = 'b';
                break;
            }
            k -= n - 1 - i;
        }

        cout << s << endl;
    }
    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Day 43 B. K-th Beautiful String 的相关文章

随机推荐