CF#629(Div.3)B. 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):

1. aaabb
2. aabab
3. aabba
4. abaab
5. ababa
6. abbaa
7. baaab
8. baaba
9. babaa
10.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. InputThe 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)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的字符串由字典排序规律分别把每个不同的字符串从1到N排序。

输入:
第一行给出一个测试组数T。
第二行T个测试,第一个n代表字符串长度,第二个k 代表字符串序号。

输出:
该序号对应的字符串。

思路:
找每个字符串中两个b对应的位置和规律。

在这里插入图片描述
如上图所示,b的位置分别按等差数列递增1,2,3,4……n-1,按规律算出两个b的位置,代码如下:

#include<bits/stdc++.h>
using namespace std;
char a[200005]; 
int  main(){
    int c,b;
    int t;    
    scanf("%d",&t); 
    while(t--)    
    {  
       int j=1,r=0;    
       scanf("%d%d",&c,&b);       
       while(b>r)   
       //由此算等差数列1+2+3+……+j>=序列号        
       {            
          r+=j;            
          j++;        
       }        
       int i;
       for(int i=0;i<c;i++)   //将数组A从0到n-1赋值为a,也可以用fill()函数: fill(a,a+c,'a');
       {
          a[i]='a';
       }      
       a[c-j]='b';   //第一个位置b的下标        
       a[c-j+r-b+1]='b';  //第二个位置b的下标        
       for(i=0; i<c; i++)            
       printf("%c",a[i]);        
       printf("\n");    
       }    
    return 0;
   }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值