CCF 202012-2 期末预测之最佳阈值 (结构体排序&前缀和查分)

传送门

思路:

题意所求答案即为所有比当前 y_{i} 大的 y_{j} 对应的 result_{j}==1 的个数加上比所有当前 y_{i} 小的 y_{j} 对应的 result_{j}==0 的个数和。

原理还是很简单的,针对1e5的数据直接写一个结构体以 y_{i} 为关键值进行排序,再利用前缀和查分计算答案即可。

需注意答案要求最大的 y_{i} 值,且过程中注意题目中 result_{i}==0 时的条件,所以利用map判断当前 y_{i} 的初始位置对 result_{i}==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);
        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;
            pre0[i] = i-pre1[i];
//            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"){
                pos = i-1;
                mp.put(a[i].x, "1");
            }
//            System.out.println("pos: " + pos);
            int res = pre1[n]-pre1[i - 1]+pre0[pos]-pre0[1];
//            System.out.println("res: " + res);
            if (res >= tmp) {
                if (a[i].x > ans) {
                    tmp = res;
                    ans = a[i].x;
                }
            }
        }
        System.out.println(ans);
    }
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/114959735