给出 n 个整数 a₁ … aₙ 和整数 k。 输出满足 |aᵢ − aⱼ| ≤ k 的位置对 i < j 有多少对。 值相同但位置不同,算作不同的数。 同两个位置只是交换顺序(i, j 与 j, i)算一对。 若 n = 1,答案为 0。 第一行给出 n 和 k,第二行给出用空格隔开的 a₁ … aₙ。
输入
1 ≤ n ≤ 10,000,−2×10⁹ ≤ aᵢ ≤ 2×10⁹,0 ≤ k ≤ 10⁹
输出
对数
样例 1 · stdin
5 3
1 9 4 7 3
stdout
5
样例 2 · stdin
2 1000000000
-2000000000 2000000000
stdout
0
main.py
错误列表00F8 ↓ · ⇧F8 ↑
输入(stdin)
运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。
$ 就绪
请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。
其他语言怎么写?查看各语言题解 · 8 种语言题解
把所有两两组合都试一遍要 n²/2 = 五千万次,Craykon 会超过执行步数上限(约五千万),Python 也很慢。 排序之后,与 a[j] 相差不超过 k 的数正好是 a[j] 前面紧挨着的一段 a[i..j−1],而且 j 往右走时 i 也只往右走(双指针)。 所以排序 n log n 加扫描 2n 就够了。 排序在各语言中不同。 Python sorted()、Java Arrays.sort()、C# Array.Sort()、C++ std::sort 都按大小排数字。 Craykon 的 a.排序() 不给比较函数时,数字也从小到大排。 但 JavaScript/TypeScript 的 sort()不传比较函数时会把元素转成字符串按字典序排,于是 10 排在 9 前面,-1 排在 -2 前面——要像 a.sort((x, y) => x - y) 这样传入函数。 C 的 qsort 也通过函数指针接收比较函数,常见的 return x - y; 在 2×10⁹ − (−2×10⁹) 时 int 溢出,顺序会颠倒——要用 (x > y) - (x < y) 只比较大小。 双指针里的 a[j] - a[i] 也有同样的溢出:差可达 4×10⁹,Java、C#、C、C++ 要转成 long/long long 再相减,否则例 2 会输出 1。 另外条件是「不超过」,所以只在差 > k 时移动 i——写成 >= k 就移动,k = 0 时会漏掉相同值组成的对。
Pythonmain.py · 12 行
n, k = map(int, input().split())a = sorted(map(int, input().split()))# 정렬하면 a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다.# j가 오른쪽으로 갈수록 구간의 왼쪽 끝 i도 오른쪽으로만 간다(두 포인터).count = 0i = 0for j in range(n): while a[j] - a[i] > k: i += 1 count += j - i # a[i..j-1]이 모두 짝이 된다print(count)
JavaScriptmain.js · 12 行
const [n, k, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// sort()에 비교 함수를 넘기지 않으면 문자열로 바꿔 사전 순으로 늘어놓는다(10이 9보다 앞)a.sort((x, y) => x - y);// a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다.let count = 0;let i = 0;for (let j = 0; j < n; j++) { while (a[j] - a[i] > k) i++; count += j - i;}console.log(count);
TypeScriptmain.ts · 14 行
import { readFileSync } from "node:fs";const [n, k, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// sort()에 비교 함수를 넘기지 않으면 문자열로 바꿔 사전 순으로 늘어놓는다(10이 9보다 앞)a.sort((x: number, y: number): number => x - y);// a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다.let count = 0;let i = 0;for (let j = 0; j < n; j++) { while (a[j] - a[i] > k) i++; count += j - i;}console.log(count);
JavaMain.java · 27 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import java.util.StringTokenizer;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] a = new int[n]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); // a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다. long count = 0; int i = 0; for (int j = 0; j < n; j++) { while ((long) a[j] - a[i] > k) i++; // 차이는 4×10⁹까지라 long으로 뺀다 count += j - i; } System.out.println(count); }}
C#Main.cs · 24 行
using System;using System.Linq;class Program{ static void Main() { string[] first = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); int n = int.Parse(first[0]); long k = long.Parse(first[1]); long[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToArray(); Array.Sort(a); // a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다. long count = 0; int i = 0; for (int j = 0; j < n; j++) { while (a[j] - a[i] > k) i++; // long이라 4×10⁹ 차이도 넘치지 않는다 count += j - i; } Console.WriteLine(count); }}
C++main.cpp · 21 行
#include <algorithm>#include <iostream>#include <vector>int main() { int n; long long k; std::cin >> n >> k; std::vector<long long> a(n); for (long long& x : a) std::cin >> x; std::sort(a.begin(), a.end()); // a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다. long long count = 0; int i = 0; for (int j = 0; j < n; j++) { while (a[j] - a[i] > k) i++; count += j - i; } std::cout << count << "\n";}
Cmain.c · 27 行
#include <stdio.h>#include <stdlib.h>static int a[10000];/* qsort에 넘기는 비교 함수. x - y로 돌려주면 int를 넘칠 수 있어서 크기만 비교한다. */static int ascending(const void* p, const void* q) { int x = *(const int*)p, y = *(const int*)q; return (x > y) - (x < y);}int main(void) { int n, k; scanf("%d %d", &n, &k); for (int i = 0; i < n; i++) scanf("%d", &a[i]); qsort(a, n, sizeof a[0], ascending); /* a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다. */ long long count = 0; int i = 0; for (int j = 0; j < n; j++) { while ((long long)a[j] - a[i] > k) i++; /* 차이는 4×10⁹까지 */ count += j - i; } printf("%lld\n", count); return 0;}
Craykonmain.cray · 19 行
첫줄 = 控制台.读数字();n = 첫줄[0];k = 첫줄[1];a = 控制台.读数字();// 기준 함수를 주지 않으면 수는 작은 것부터 늘어놓는다a.排序();// a[j]와 차이가 k 이하인 것은 a[j] 바로 앞의 한 구간이다. 왼쪽 끝 i는 오른쪽으로만 간다.count = 0;i = 0;循环 (j = 0; j < n; j++){ 当 (a[j] - a[i] > k) { i += 1; } count += j - i;}控制台.输出(count);