静态代码扫描服务
题目描述
静态扫描快速识别源代码的缺陷,静态扫描的结果以扫描报告作为输出:
- 文件扫描的成本和文件大小相关,如果文件大小为 �N ,则扫描成本为 �N 个金币
- 扫描报告的缓存成本和文件大小无关,每缓存一个报告需要 �M 个金币
- 扫描报告缓存后,后继再碰到该文件则不需要扫描成本,直接获取缓存结果
给出源代码文件标识序列和文件大小序列,求解采用合理的缓存策略,最少需要的金币数。
输入描述
第一行为缓存一个报告金币数 M,1≤M≤100
第二行为文件标识序列:F1,F2,F3...Fn,其中1≤N≤10000,1≤Fi≤1000
第三行为文件大小序列:S1,S2,S3...Sn,其中1≤N≤10000,1≤Si≤10
输出描述
采用合理的缓存策略,需要的最少金币数
示例一
输入
5
1 2 2 1 2 3 4
1 1 1 1 1 1 1
输出
7
说明
文件大小相同,扫描成本均为1个金币。缓存任意文件均不合算,因而最少成本为7金币
示例二
输入
5
2 2 2 2 2 5 2 2 2
3 3 3 3 3 1 3 3 3
输出
9
说明
2号文件出现了8次,扫描加缓存成本共计3+5=8
,不缓存成本为3*8=24
,显然缓存更优,最优成本为8+1=9
。
Java
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)){
int M = in.nextInt();
in.nextLine();
String fI = in.nextLine();
String fS = in.nextLine();
int res = solution(M, fI, fS);
System.out.println(res);
}
}
private static int solution(int m, String fI, String fS) {
HashMap<Integer, Integer> fCost = new HashMap<>();
HashMap<Integer, Integer> fSize = new HashMap<>();
String[] ids = fI.split(" ");
String[] sizes = fS.split(" ");
for (int i = 0; i < ids.length; i++) {
int id = Integer.parseInt(ids[i]);
int size = Integer.parseInt(sizes[i]);
fCost.put(id, fCost.getOrDefault(id, 0) + 1);
fSize.put(id, size);
}
int sum = 0;
for (Integer id : fCost.keySet()) {
int total = fCost.get(id) * fSize.get(id);
total = Math.min(total, m + fSize.get(id));
sum += total;
}
return sum;
}
}