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

A. Stages

题目链接

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.

There are nn stages available. The rocket must contain exactly kk of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.

For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — 2626 tons.

Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.

Input

The first line of input contains two integers — nn and kk (1≤k≤n≤501≤k≤n≤50) – the number of available stages and the number of stages to use in the rocket.

The second line contains string ss, which consists of exactly nn lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.

Output

Print a single integer — the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.

题意:从长度为n的字符串中取出k个字符组成一个新的字符串,要求各个字符之间不能在a~z的排序中相邻,求出组成的最小的字符串的权值。(a的权值为1,b为2,依次类推)

思路:将字符串的字符排序,从头开始取,贪心的取不相邻的即可,如果可以取到k个长度,则该结果就是答案,取不到则不存在答案,输出-1.

#include<bits/stdc++.h>
using namespace std;
const int maxn=int(1e6)+10;
int main() {
	int n,m;
	char str[maxn];
	while(~scanf("%d %d",&n,&m)) {
		scanf("%s",str);
		sort(str,str+n);
		int i=1;
		int top=1;
		int tmp=str[0];
		int ans=str[0]-'a'+1;
		while(i<n) {
			if(top==m)
				break;
			if(str[i]-tmp>=2) {
				ans+=str[i]-'a'+1;
				tmp=str[i];
				top++;
			}
			i++;
		}
		if(top<m)
			printf("-1\n");
		else
			printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40160605/article/details/81255679