一、Problem
输入
输入一行包含一个整数 n。
接下来N行,每行包含一个单词 Ai。
输出
输出最大价值之和。
数据范围
对于20%的评测用例,1 ≤ n ≤ 10, 且首字母均相同。
对于另外30%的评测用例,1 ≤ n ≤ 10,单词长度均相同。
对于80%的评测用例,1 ≤ n ≤ 1000。
对于100%的评测用例,1 ≤ n ≤ 100000,单词长度不超过20个字符且均为小写字母。
5
jmcoding
lq
hello
sto
orz
867
二、Solution
方法一:贪心
- 字符串的长度和首字母是固定的。
- 所以只需要预处理一下字符串的 len * C 到数组 val 中,然后升序排列数组 val,因为可以使得 len * C 尽量最大…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
String[] ss;
long[] work(int N) {
long[] val = new long[N];
for (int i = 0; i < N; i++) {
val[i] = ss[i].length() * (ss[i].charAt(0)-'a'+1);
}
return val;
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int N = sc.nextInt();
ss = new String[N];
for (int i = 0; i < N; i++) {
ss[i] = sc.next();
}
long[] val = work(N);
Arrays.sort(val);
long sum = 0;
for (int i = 0; i < N; i++) {
sum += (i+1)*val[i];
}
System.out.println(sum);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
复杂度分析
- 时间复杂度:,
- 空间复杂度:,