求求指点迷津

P1678 烦恼的高考志愿

swan999 @ 2023-12-30 16:56:47

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    static int N = 100010;
    static int[] a = new int[N];
    static int[] b = new int[N];
    static int get(int num,int v){
        return Math.abs(a[num] - v);
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        int m = sc.nextInt();
        int n = sc.nextInt();
        for (int i = 0; i < m; i++)
            a[i] = sc.nextInt();
        for(int j = 0;j < n;j ++)
            b[j] = sc.nextInt();
        Arrays.sort(a,0,m);
        int l;
        int r;
        long res = 0;
        for(int i = 0;i < n;i ++){
            int v = b[i];
            l = 0;
            r = m - 1;
            while(l < r){
                int mid = (l + r) / 2;
                if(get(mid,v) <= get(mid + 1,v)) r = mid;
                else l = mid + 1;
            }
            res += Math.abs(b[i] - a[l]);
        }
        System.out.println(res);
    }
}

|