Pairs

Given  integers, count the number of pairs of integers whose difference is .

Input Format

The first line contains  and 
The second line contains  numbers of the set. All the  numbers are unique.

Constraints

  • Each integer will be greater than  and at least  smaller than .

Output Format

An integer that tells the number of pairs of integers whose difference is .

Sample Input

5 2  
1 5 3 4 2  

Sample Output

3

Explanation

There are 3 pairs of integers in the set with a difference of 2.

 

二分查找就okl了   竟然不支持预编译指令..

/* ***********************************************
Author        :guanjun
Created Time  :2016/11/6 21:52:07
File Name     :Pairs.cpp
************************************************ */
#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 10010
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
priority_queue<int,vector<int>,greater<int> >pq;
struct Node{
    int x,y;
};
struct cmp{
    bool operator()(Node a,Node b){
        if(a.x==b.x) return a.y> b.y;
        return a.x>b.x;
    }
};

bool cmp(int a,int b){
    return a>b;
}
int a[100010];
int main()
{
    //#ifndef ONLINE_JUDGE
    //freopen("in.txt","r",stdin);
    //#endif
    //freopen("out.txt","w",stdout);
    int n,k;
    while(cin>>n>>k){
        int Max=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            if(a[i]>Max)Max=a[i];
        }
        sort(a+1,a+1+n);
        int num=0;
        for(int i=1;i<=n;i++){
            int x=a[i]+k;
            if(x>Max)break;
            int p=lower_bound(a+i,a+1+n,x)-a-i;
            //cout<<"p "<<p<<endl;  偏移量
            if(p<=n-i){
                if(a[i+p]==x)num++;
            }
        }
        cout<<num<<endl;
    }
    return 0;
}

 

posted on 2016-11-06 22:11  Beserious  阅读(430)  评论(0编辑  收藏  举报