Codeforces Round #629 (Div.3) B(思维,字符串,二分)

链接
B. K-th Beautiful String
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
outputCopy
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
题意:给定字符串长度,按照字典序,输出第k个变化的字符串
思路:找规律,1 2 3 4…

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int T;
	cin >> T;
	while(T--){
		int	n,k;
		cin >> n >> k;
		k -= 1;
		string s;
		for (int i = 0; i < n; i++){
			s.push_back('a');
		}
		int i = n-2;
		
		while(k >= n-1-i){
			k -= n-1-i;
			i--;
		}
		
		s[i] = 'b';
		s[n-1-k] = 'b';
		cout << s << "\n";
	}
	return 0;
}

自己写的太麻烦

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 7e4 + 10;
signed main(){
	int T,a[N];
	for(int i = 0; i < N; i++)
		a[i] = i * (i+1) / 2;
	cin >> T;
	int n,k;
	while (T--){
		cin >> n >> k;
		int l = 0,r = N-1;
		while(l < r){
			int mid = (l+r+1) >> 1;
			if (a[mid] >= k) r = mid - 1;
			else l = mid;
		}
		int pos1 = l + 1;
		int pos2 = k - a[l] - 1;
		for (int i = n-1; i >= 0 ; i--){
			if (i == pos1||i == pos2) cout << "b";
			else cout << "a";
		}
		cout << "\n";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值