Codeforces Round #466 (Div. 2) Phone Numbers

C. Phone Numbers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 is not lexicographically smaller than a.

Input

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

Output the string t conforming to the requirements above.

It's guaranteed that the answer exists.

Examples
input
Copy
3 3
abc
output
aca
input
Copy
3 2
abc
output
ac
input
Copy
3 3
ayy
output
yaa
input
Copy
2 3
ba
output
baa
Note

In the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca.

 

找规律, 构造题

 构造方法

k>n
  贪心的加最小的,前面和s一样

k<=n
   从后往前扫描

  如果是'z'

  则用最小的

  不然用可行的比原字母大一的

  并结束构造

  让前面的和s相同
代码:
 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<map>
 6 map<int,int> maps;
 7 char s[300000];
 8 char a[300000];
 9 int main(){
10     int n,k;
11     scanf("%d%d",&n,&k);
12     scanf("%s",a);
13     char MIN = 'a';
14     for(int i=0;i<n;i++){
15         if(i==0||a[i]<MIN)
16             MIN = a[i];
17         s[i]=a[i];
18         maps[(int)a[i]]=1;
19     }
20     for(int i=n;i<k;i++){
21         s[i]=MIN;
22     }
23     int pt=0;
24     if(n>=k){
25         for(int i=k-1;i>=0&&pt==0;i--){
26             int p=s[i];
27             for(int j=p+1;j<='z'+1&&pt==0;j++){
28                 if(j=='z'+1){
29                     s[i]=MIN;
30                 }
31                 else if(maps[j]){
32                     s[i]=j;
33                     pt=1;
34                     break;
35                 }
36             }
37         }
38     }
39     for(int i=0;i<k;i++)
40         putchar(s[i]);
41     return 0;
42 }

 

posted @ 2018-03-09 10:12  晓风微微  阅读(223)  评论(0编辑  收藏  举报