codeforces940 C. Phone Numbers【贪心】

C. Phone Numbers

time limit per test2 seconds
memory limit per test256 megabytes
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.

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

inputCopy

3 3
abc

output

aca

inputCopy

3 2
abc

output

ac

inputCopy

3 3
ayy

output

yaa

inputCopy

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的字符串,规定新的字符串不能出现之前没有出现的字母

分析:
<1>.首先考虑当 k > n时,很显然,我们只需在原字符串后面加上出现的字典序最小的字符即可。
<2>.否则,我们贪心的从后往前找如果该出现过的下一个字符即可,然后之后都赋为最小的字符

参考代码

#include

using namespace std;

#define ll long long

int h[100000];

int main(){
    ios_base::sync_with_stdio(0);
    int n,m;cin>>n>>m;
    string s1;cin>>s1;
    string s = s1;
    sort(s.begin(),s.end());
    vector<char> c;
    c.push_back(s[0]);
    for (int i = 1;i < s.size();i++) {
        if(s[i] == s[i - 1]) continue;
        c.push_back(s[i]);
    }
    string res;
    if(m > n) {
        res += s1;
        while ((int)res.size() < m) res = res + s[0];
        cout<return 0;
    }
    res = s1.substr(0,m);
    for (int i = m - 1;i >= 0;i--) {
        char d = res[i];
        if(d == c.back()) continue;
        for (int j = c.size() - 1;j >= 0;j--) {
            if(c[j] == d) {
                res[i] = c[j+1];
                for (int k = i + 1;k < m;k++) {
                    res[k] = s[0];
                }
                cout<return 0;
            }
        }
    }
    return 0;
}
  • 如有错误或遗漏,请私聊下UP,thx

你可能感兴趣的:(----,贪心----)