cf - 940C - Phone Numbers - ( 构造 )

题目链接:点击进入
题意

给你一个长度为 n 的字符串 s ,让你找到长度为 k 的且字典最小字符串 t ,使其字母集是 s 字母集的子集,并且 s 在字典上小于 t 。答案肯定存在。

思路

如果 n < k ,那么直接在原字符串上加上( k - n ) 个 字母集中字典序最小的字母 即可;
如果 n >= k , 从 s串 的前 k 位开始,倒序枚举每一位,同时在字母集中查找是否存在比 这一位的字母 字典序更大的字母:
要是有,直接将这位之前的s串正常输出,这一位输出你找到的那个字母,后面的全部输出字母集中字典序最小的字母;
要是没有,接着往前枚举查找,一直到找到为止;

代码
//#pragma GCC optimize(2) 
//#pragma GCC optimize(3) 
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131 
#define INF 0x3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
//#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps=1e-7;
const double pai=acos(-1.0);
const int N=2e4+10;
const int maxn=1e6+10;
const int mod=1e9+7;
int n,k,cnt;
string s;
bool vis[210];
char p[maxn];
int main( )
{
//	ios::sync_with_stdio(false);?
    cin>>n>>k;
    cin>>s;
    for(int i=0;i<n;i++)
    {
    	if(!vis[s[i]])
    	{
    		p[cnt++]=s[i];
    		vis[s[i]]=1;
		}
	}
	sort(p,p+cnt);
	if(n<k) 
    {
    	cout<<s;
    	for(int i=1;i<=k-n;i++)
		cout<<p[0];
    	return 0;
	}
    for(int i=k-1;i>=0;i--)
    {
    	int pos=upper_bound(p,p+cnt,s[i])-p;
    	if(pos!=cnt)
		{
			for(int j=0;j<i;j++) cout<<s[j];
			cout<<p[pos];
			for(int j=i+1;j<k;j++) cout<<p[0];
			break;
		}
	}
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值