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

B. K-th Beautiful String

题目链接-B. K-th Beautiful String
在这里插入图片描述
在这里插入图片描述
题目大意
长度为n的字符串包含 n 2 n−2 a a 2 2 b b ,求按照字典序排列输出第 k k 个字符串

解题思路

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

附上代码

#include<bits/stdc++.h>
#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;
}

发布了175 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/105150742