Codeforces Round #499 (Div. 2) A Stages (java)
型別:貪心
題意:給你一堆字元a-z(n個),然後選k個字元組裝起來,要求後一個字元不能是前一個字元的相鄰
題解:開個27的陣列,從a到z貪心,標記選取的前一個字元,記錄字元權值和,記錄選取個數,選取個數不達到k則輸出-1
import java.util.Scanner;
public class A{
public static void main(String[] args) {
int a[]=new int[27];
Scanner kb = new Scanner(System.in);
int n=kb.nextInt();
int t=kb.nextInt();
String str=kb.next();
char ch[]=str.toCharArray();
for(int i=0;i<ch.length;i++) {
int b=ch[i]-'a'+1;
a[b]++;
}
int bj=0;
int bj1=-1;
int sum=0;
for(int i=1;i<=26&&bj<t;i++) {
if (a[i]>0&&bj1!=i-1) {
sum+=i;
bj1=i;
bj++;
}
}
if(bj<t) {
System.out.println(-1);
}else {
System.out.println(sum);
}
kb.close();
}
}