社区讨论

92分,第3个WA,求个佬看看(java版的)

P1102A-B 数对参与者 5已保存回复 5

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
5 条
当前快照
1 份
快照标识符
@lo32ssvn
此快照首次捕获于
2023/10/23 23:52
2 年前
此快照最后确认于
2023/10/23 23:52
2 年前
查看原帖
CPP

import java.util.*;



public class Main {

    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int c = sc.nextInt();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        int[] a = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            a[i]=list.get(i);
        }
        int num = 0;
        for (int i = 0; i < a.length; i++) {
            int b = a[a.length-1-i];
            if (b-c<=0){
                continue;
            }
            int d = b-c;
            int left = left(a, d);
            int right = right(a, d);
            if (right == -1){
                continue;
            } else if (right - left == 1) {
                num+=2;
            }else if (right == left){
                num++;
            }else {
                num+=(right-left)+1;
            }

        }
        System.out.println(num);

    }
    public static int left(int[] arr,int key){
        int low = 0;
        int high = arr.length - 1;
        int candedate = -1 ;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = arr[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else{
                candedate = mid;
                high = mid - 1;
            }
                 // key found
        }
        return candedate;  // key not found.
    }

    public static int right(int[] arr,int key){
        int low = 0;
        int high = arr.length - 1;
        int candedate = -1 ;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = arr[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else{
                candedate = mid;
                low = mid + 1;
            }
            // key found
        }
        return candedate;  // key not found.
    }

}

回复

5 条回复,欢迎继续交流。

正在加载回复...