Loading

HDU-5178 pairs

pairs

给出n个数字,问有多少个对数字的差的绝对值小于等于 k

尺取

排序之后,用尺取,固定左端,看看多少个数字 k>=num[l] 即可

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
int num[maxn];

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        int n, k;
        scanf("%d%d", &n, &k);
        for(int i=0; i<n; i++) scanf("%d", &num[i]);
        sort(num, num + n);
        ll ans = 0;
        int l = 0, r = 0;
        while(l < n)
        {
            while(r < n && num[r] - num[l] <= k)
                r++;
            ans += r - l - 1;
            l++;
        }
        printf("%lld\n", ans);
    }

    return 0;
}
posted @ 2022-05-13 01:26  dgsvygd  阅读(24)  评论(0编辑  收藏  举报