第一题
package ccf202012; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class p1 { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); int[] w = new int[n]; int[] score = new int[n]; long relu = 0; for (int i = 0; i < n; i++) { String[] temp = bf.readLine().split(" "); w[i] = Integer.parseInt(temp[0]); score[i] = Integer.parseInt(temp[1]); relu += w[i] * score[i]; } if (relu < 0) { System.out.println(0); } else { System.out.println(relu); } } }
第二题(使用前缀和,hashset去重)
package ccf202012; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class p2f { static class Data { public int y; public int result; } public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int m = Integer.parseInt(bf.readLine()); ArrayList<Data> list = new ArrayList<>(); for (int i = 0; i < m; i++) { String[] temp = bf.readLine().split(" "); Data data = new Data(); data.y = Integer.parseInt(temp[0]); data.result = Integer.parseInt(temp[1]); list.add(data); } list.sort((a, b) -> a.y - b.y); //前缀和用来计算某一个区段内的数值和 int[] sum = new int[m + 1];//sum是用来求前缀和的,sum[i]表示前i个人有多少个过的 sum[0] = 0; int index = 1; for (Data data : list) { sum[index] = sum[index-1]+data.result; index++; } //预测正确数目 = 阈值小于自己且挂科 + 阈值大于等于自己且未挂科 //假设此时为i,则有 预测正确数目 = [0,i)中不及格(在本题中相当于i-sum[i],即用前i个人减去及格人数) + [i,m]中及格 int max = 0; long output = 0; int localSum; Set<Integer> set = new HashSet<>(); for (int i = 0; i < m; i++) { int y = list.get(i).y; localSum = 0; if (set.contains(y))//当数字再次出现时跳过 continue; set.add(y); long sum1 = sum[m] - sum[i];//自己及之后的 1 的个数 long sum0 = i - sum[i];//不包含自己的之前的 0 的个数 localSum += sum0 + sum1;//预测正确数目 if (localSum >= max) { max = localSum; output = y; } } System.out.println(output); } }