Codeforces Round #499 (Div. 2) ---- A Stages

这题一开始没有很理解题意,结果瞎写过的,之后fst了。。。

给我们一个串,去拿一些字母,字典序大于这个字母的第一个不能要,小于这个字母的不能要,求拿到最小的价值

根据贪心的思想,我们肯定优先拿最小的字母,所以对这个字符串排个序,从最小的开始拿就好

fst的原因就是计数的cnt写出了问题,在test24的位置wa了,以后注意下极端情况。

代码如下

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int gcd(int a,int b){if (b == 0) return a; return gcd(b , a%b);}
int lcm(int a, int b){ return a/gcd(a,b)*b;}
int main(){
    int n,k;
    cin >> n >> k;
    string line;
    cin >> line;
    sort(line.begin(), line.end());
    //cout << line << endl;
    int ans = line[0] - 'a' + 1,cnt = 1;
    char pre = line[0];
    for (int i=1; i<line.size(); i++) {
        if (cnt == k) break;
        if (line[i] - pre > 1) {
            ans += line[i] - 'a' + 1; cnt++; pre = line[i];
        }
    }
   //cout << ans << ' ' << cnt << endl;
     if (cnt != k) cout << -1 << endl;
    else cout <<ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CCCCTong/article/details/81259187