HDU 5178 Pairs (linear probing problem)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.