尺取求符合题意的答案


/*
John has nn points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,…,n?1)(x[i],0),(i=0,1,2,…,n?1). He wants to know how many pairs<a,b><a,b> that |x[b]?x[a]|≤k.(a<b)|x[b]?x[a]|≤k.(a<b)
Input
The first line contains a single integer TT (about 5), indicating the number of cases. 
Each test case begins with two integers n,k(1≤n≤100000,1≤k≤109)n,k(1≤n≤100000,1≤k≤109). 
Next nn lines contain an integer x[i](?109≤x[i]≤109)x[i](?109≤x[i]≤109), means the X coordinates.
Output
For each case, output an integer means how many pairs<a,b><a,b> that |x[b]?x[a]|≤k|x[b]?x[a]|≤k.
Sample Input
2
5 5
-100
0
100
101
102
5 300
-100
0
100
101
102
Sample Output
3
10
*/ 

/*
题意    求数据段中有几对  的 值 小于等于   k;

这题我是用  尺取 求解的

答案如下 
*/
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long ll;
bool cmp(ll a,ll b)
{
    return a<b;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        ll m;
        ll l;
        scanf("%lld%lld",&m,&l);
        ll a[100100],b[100100];
        for(int i=0;i<m;i++)
        {
            scanf("%lld",&a[i]);
        }
        sort(a,a+m,cmp);
        ll i=0,j=1;
        b[0] = a[0];
        b[1] = a[1];
        ll s=0;
        while(j<m)
        {
            if(b[j]-b[i]>l)
            {
                i++;
            }
            else
            {
                s +=j-i;
                j++;
                b[j] = a[j];
    
            }
        }
        printf("%lld\n",s);
    }
}

猜你喜欢

转载自blog.csdn.net/lijianzhong1/article/details/81268060