Codeforces--1328B--K-th Beautiful String

題目描述:
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.
輸入描述:
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.
輸出描述:
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).
輸入:
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
輸出:
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
題意:
n−2個aaa和222個bbb組成的字符串的第kkk小的字典序的字符串是什麼。
題解
找規律
cnt[i]記錄倒數第2個b,所處字串倒數第i位時,對應的形態數量
sum[i]記錄cnt[i]的前綴和
代碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;

const int maxn = 100000 + 5;
int sum[maxn],a[maxn];
char s[maxn];

void init(){
    for(int i = 2; i <= 100000; i ++){
        a[i] = a[i - 1] + 1;
        sum[i] = sum[i - 1] + a[i];
    }
}

int main(){
    int t,n,k;
    scanf("%d",&t);
    init();
    while(t--){
        scanf("%d%d",&n,&k);
        int i,j;
        for(i = 2; i <= n; i ++){
            if(sum[i] >= k) break;
        }
        j = i;
        k -= sum[j - 1];
        for(int i = 1; i <= n; i ++) s[i] = 'a';
        s[n + 1] =  '\0';
		s[n - j + 1]='b';
		s[n - k + 1]='b';
		printf("%s\n",s + 1);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章