Untitled
unknown
plain_text
4 years ago
1.2 kB
6
Indexable
package com.company; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { static int pair_difference_smaller_than_K(ArrayList<Integer> a, int N, int K) { if (Collections.max(a)) return N * (N - 1) / 2; if (K == 0) return 0; // sắp xếp Collections.sort(a); // biến kq int count_pair = 0; // duyệt for (int i = 0; i < N; i++) { // tìm kiếm nhị phân giá trị gần nhất để hiệu với a[i] >= K int temp = Collections.binarySearch(a, a.get(i) + K); if (temp < 0) temp = -temp - 1; count_pair += (temp - 1 - i); } return count_pair; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test_case = sc.nextInt(); while (test_case-- > 0) { int N = sc.nextInt(), K = sc.nextInt(); ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < N; i++) { arr.add(sc.nextInt()); } System.out.println(pair_difference_smaller_than_K(arr, N, K)); } } }
Editor is loading...