https://vjudge.net/contest/241732#problem/A
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
Note
In the first example, the following rockets satisfy the condition:
Rocket "adx" has the minimal weight, so the answer is 2929.
In the second example, target rocket is "belo". Its weight is 2+5+12+15=342+5+12+15=34.
In the third example, n=k=2n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
题意:给出n个字母,找出k个字母,保证和最小,且每个字母在字母表上的位置不能相邻,中间至少隔一个字母。
提交了n次都不对
一个地方是这里,本来用的是两个if,后来发现应该是if else,不符合if就不应该再让它往下走了:
if(a[i]-a[j]==1)
i++;
else
{
sum=sum+a[i];
t++;
j=i;
i++;
}
还有一个地方就是应该有前面的去选后面的,而不是由后面的字母去选前面的
这两个错误都是比较内在逻辑的,轻易看不出来,以后写代码的时候可能要注意一下思维。
代码:
#include
#include
#include
using namespace std;
int main()
{
int n,k,i,j,sum,t=1;
scanf("%d%d",&n,&k);
char a[100];
scanf("%s",a);
sort(a,a+n);
sum=a[0];
if(k==1)
printf("%d",a[0]-96);
else
{
i=1;
j=0;
n=unique(a,a+n)-a;//操作是去重,得出的n是字符串中字母的种类个数
while(t!=k&&i
本来应该用尺取做,但是不太会尺取。。。