AcWing 3298. 期末预测之最佳阈值-y总-前缀和-java版本
原题链接
中等
作者:
西红柿炒番茄_7
,
2024-12-04 16:07:35
,
所有人可见
,
阅读 1
Java代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] ints = new int[2][n + 1];
ArrayList<Pair> pairs = new ArrayList<>();
pairs.add(new Pair(-1,-1));
for (int j = 1;j<=n;j++) {
int x = sc.nextInt();
int y = sc.nextInt();
Pair pair = new Pair(x, y);
pairs.add(pair);
}
Collections.sort(pairs, (o1,o2)-> {return o1.x-o2.x;});
//构建前缀和
for (int i = 0 ;i<2;i++) {
for (int j = 1;j<=n;j++) {
ints[i][j] = ints[i][j-1] + (pairs.get(j).y == i ? 1 : 0);
}
}
int cnt = -1,res = 0;
for (int i = 1 ;i<=n;i++) {
int t = ints[0][i-1] + ints[1][n] - ints[1][i-1];
if (t >= cnt) {cnt = t; res = pairs.get(i).x;}
while (i+1<=n && pairs.get(i).x == pairs.get(i+1).x) i++;
}
System.out.println(res);
}
static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}