Codeforces Round #629 (Div. 3) B. K-th Beautiful String

B. K-th Beautiful String

题目链接-B. K-th Beautiful String
Codeforces Round #629 (Div. 3) B. K-th Beautiful String_第1张图片
Codeforces Round #629 (Div. 3) B. K-th Beautiful String_第2张图片
题目大意
长度为n的字符串包含 n − 2 n−2 n2 a a a 2 2 2 b b b,求按照字典序排列输出第 k k k个字符串

解题思路

  • 第一个 b b b在倒数第二位有1个字符串,在倒数第三位有2个字符串…在倒数第 n n n位时有 n − 1 n-1 n1个字符串
  • 可以根据第一个 b b b的位置对字符串进行分组,然后找到第 k k k个字符串在第几组里即可,然后再推出第二个 b b b的位置即可
  • 记得我们刚开始找的 b b b的位置是倒数的,假设 b b b在倒数第i位上,那么b就在整数第 n + 1 − i n+1-i n+1i位上
  • 具体操作见代码

附上代码

#include
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+5;
typedef long long ll;
typedef pair<int,int> PII;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int t;
	cin>>t;
	while(t--){
		int n,k;
		cin>>n>>k;
		int x=0,tmp;
		for(int i=1;i<=n;i++){
			tmp=i*(i-1)/2;
			if(tmp>=k){
				x=i-1;
				break;
			}
		}
		int y=k-x*(x-1)/2-1;
		x=n-x;
		y=n-y;
		for(int i=1;i<=n;i++){
			if(i==x||i==y) cout<<"b";
			else cout<<"a";
		}
		cout<<endl;
	}
		return 0;
}

你可能感兴趣的:(codeforces)