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.
Examples
Input
5 3 xyabd
Output
29
Input
7 4 problem
Output
34
Input
2 2 ab
Output
-1
Input
12 1 abaabbaaabbb
Output
1
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int m,n;
while(cin>>m>>n)
{
char s[60],r[60];
cin>>s;
sort(s,s+m);
r[0]=s[0];
int i,j;
for(j=1,i=1;i<m;i++)
{
if(s[i-1]!=s[i])
r[j++]=s[i];
}
int sum=r[0]-96,k=1,p=j;
if(n>m)
cout<<"-1\n";
else if(n==1)
{
cout<<sum<<endl;
}
else
{
for(i=0;i<p-1;i++)
{
if(r[i+1]-r[i]!=1)
{
sum=sum+r[i+1]-96;
k++;
}
else if(r[i+1]-r[i]==1&&i+2<p)
{
sum=sum+r[i+2]-96;
k++;
i++;
}
if(k==n)
break;
}
if(n==k)
cout<<sum<<endl;
else
cout<<"-1\n";
}
}
return 0;
}
本文介绍了一个算法挑战,目标是构建由特定阶段组成的最轻火箭,每个阶段由小写字母表示,且必须遵循字母顺序和重量规则。文章探讨了如何通过算法选择最佳阶段组合,以达到最小总重量。
1642

被折叠的 条评论
为什么被折叠?



