problem Description
John had n points on the X axis, and their coordinates is (X[i],0), (i=0,1,2,..., n−1 ). He wants to know what many pairs<a,b> that |x[b]−x[a]|≤k. (A<B)
Input
5 case begins with integers n,k (1≤n≤100000,1≤k≤109 ). Next n lines contain an integer x[i] (−109≤x[i]≤109
Output
case, output a integer means how many pairs<a,b> that |x[b]−x[a]|≤k.
Sample Input
2
5 5
-0101102
-0101102
Sample Output
3
10
Source
Bestcoder Round #31
Test instructions: Given an array, ask how many pairs of <a,b> make| x[ B]− x[ A]| ≤k. (a< b)
thinking: 1, the most important thing is to solve the problem of overtime, otherwise, according to the violence must be timed out.
2, resolving timeouts, here's a way.
First sort this array from small to large, then I start from 0, TMP starts from 0, if the value is less than or equal to K, tmp++ until >k stop ,
ans plus this value. Next time, i+1, before the I and K can, then and
i
< span class= "Mo" > +1 more can, all k continue to run backwards, so the complexity is greatly reduced.
specific look at the code
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5#include <stdlib.h>6#include <cmath>7 using namespacestd;8 #defineN 1000069 #definell Long LongTen intn,k; One intA[n]; A intMain () - { - intT; thescanf"%d",&t); - while(t--) - { -scanf"%d%d",&n,&k); + for(intI=0; i<n;i++) scanf ("%d",&a[i]); -Sort (a,a+n); +ll ans=0; A inttmp=0; at for(intI=0; i<n;i++) - { - while(ABS (a[i]-a[tmp]) <=k && tmp<n) tmp++; -ans=ans+tmp-i-1; - } -printf"%i64d\n", ans); in } - return 0; to}
View Code
HDU 5178 Pairs (linear probing problem)