其他分享
首页 > 其他分享> > 【ATCOER、D - ±1 Operation 2】前缀和+排序二分

【ATCOER、D - ±1 Operation 2】前缀和+排序二分

作者:互联网

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        int N,Q;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] words = br.readLine().split("\\s+");
        N = Integer.valueOf(words[0]);
        Q = Integer.valueOf(words[1]);
        long[] A = new long[N];
        words = br.readLine().split("\\s+");
        for (int i = 0; i < N; i++) {
            A[i] = Long.valueOf(words[i]);
        }
        long[] sum = new long[N];
        Arrays.sort(A);
        for (int i = 0; i < N; i++) {
            if( i==0){
                sum[0] = A[i];
            }else{
                sum[i] = sum[i-1] + A[i];
            }
        }
        //
        for (int i = 0; i < Q; i++) {
            long x = Long.valueOf(br.readLine());
            int upper = upperBound(A,0,N,x);

            if( upper == 0){
                long ans = sum[N-1] - x*N;
                System.out.println(ans);
            }
            else if( upper < N){
                long ans = x*upper - sum[upper-1];
                ans += sum[N-1] - sum[upper-1];
                ans -= x*(N-upper);
                System.out.println(ans);
            }else{
                long ans = x*N - sum[N-1];
                System.out.println(ans);
            }
        }



    }

    public static int upperBound(long[] arr, int start, int high, long key) {
        while (start < high) {
            int mid = (start+high)/2;

            if(arr[mid] >key){
                high = mid;
            }else{
                start = mid+1;
            }
        }
        return high;
    }

}

 

标签:upper,ATCOER,前缀,int,sum,long,words,ans,Operation
来源: https://www.cnblogs.com/fishcanfly/p/16368637.html