And where the are the phone numbers?
You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.
It's guaranteed that the answer exists.
Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.
String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.
The first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t.
The second line of input contains the string s consisting of n lowercase English letters.
Output the string t conforming to the requirements above.
It's guaranteed that the answer exists.
3 3 abc
aca
3 2 abc
ac
3 3 ayy
yaa
2 3 ba
baa
题意:给你一个字符串A,让你把A变成字典序比A大1的字符串,输出即可。
思路:贪心,当n<k时,我们的长度比A长,所以必然大于A,这时直接输出A,并追加最小值(在s[i]里找最小)即可。
当n>=k时,我们的长度小于等于A,这时从右向左找(更改优先级最低的嘛),找到第一个不等于最大值的c,最大值已经不能改了,以c为标准,在s[i]里找到第一个大于c的c1,将c=c1,更改完毕,追加最小值(在s[i]里找最小)即可。
要注意一些字符可能会有重复。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#define ll long long
using namespace std;
ll n,k,vis[30];
char s[100010],mmax,mmin;
int main()
{
while(~scanf("%lld%lld",&n,&k))
{
scanf("%s",s+1);
memset(vis,0,sizeof(vis));
for(ll i=1;i<=n;i++)vis[s[i]-'a'+1]=1;
if(n<k)
{
printf("%s",s+1);
mmin=s[1];
for(ll i=1;i<=n;i++)
{
if(s[i]<mmin)mmin=s[i];
}
for(ll i=1;i<=k-n;i++)printf("%c",mmin);
printf("\n");
}
else
{
mmax=s[1];
mmin=s[1];
ll p,c;
for(ll i=1;i<=n;i++)
{
if(s[i]>mmax)mmax=s[i];
if(s[i]<mmin)mmin=s[i];
}
for(ll i=k;i>=1;i--)
{
if(s[i]==mmax)continue;
p=i;
break;
}
c=s[p]-'a'+1;
for(ll i=c+1;i<=26;i++) //此处找第一个大于c的值
{
if(vis[i]==1)
{
c=i;
break;
}
}
for(ll i=1;i<p;i++)printf("%c",s[i]);
printf("%c",c+'a'-1);
for(ll i=p+1;i<=k;i++)printf("%c",mmin);
printf("\n");
}
}
return 0;
}