思路:
题意所求答案即为所有比当前 大的 对应的 ==1 的个数加上比所有当前 小的 对应的 ==0 的个数和。
原理还是很简单的,针对1e5的数据直接写一个结构体以 为关键值进行排序,再利用前缀和查分计算答案即可。
需注意答案要求最大的 值,且过程中注意题目中 ==0 时的条件,所以利用map判断当前 的初始位置对 ==0 的情况进行查分。
代码实现:
import java.util.Scanner;
import java.util.HashMap;
import java.util.*;
class node implements Comparable<node>
{
int x, y;
public node(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(node a) {
if (this.x != a.x)
return this.x-a.x;
else
return this.y-a.y;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
node a[] = new node[100010];
for (int i = 1; i <= n; i ++){
int x = in.nextInt();
int y = in.nextInt();
a[i] = new node(x, y);
}
Arrays.sort(a, 1, n+1); //按照x升序进行排序
int [] pre1 = new int[100010];
int [] pre0 = new int[100010];
for(int i = 1; i <= n; i ++){
pre1[i] = pre1[i-1]+a[i].y; //记录i之前1的个数
pre0[i] = i-pre1[i]; //同理记录i之前0的个数
// System.out.println("i: " + i + " pre0: " + pre0[i] + " pre1: " + pre1[i]);
}
int tmp = 0, ans = 0, pos = 1;
Map<Integer, String> mp = new HashMap<Integer, String>();
for (int i = 1; i <= n; i ++) {
if( mp.get(a[i].x)!="1"){ //如果当前这个数值x都还没统计过
pos = i-1; //记录第一个x值的前面一个位置
mp.put(a[i].x, "1"); //标记其为统计过
}
// System.out.println("pos: " + pos);
//因为题目要求是>=为安全,所以对于不安全的得找比x小的数的位置pos及以前的0的个数。
int res = pre1[n]-pre1[i - 1]+pre0[pos]-pre0[1];
// System.out.println("res: " + res);
if (res >= tmp) { //更新答案
if (a[i].x > ans) { //更新找到同等答案下最大的x值
tmp = res;
ans = a[i].x;
}
}
}
System.out.println(ans);
}
}