P1102 A-B 数对

题目链接:https://www.luogu.com.cn/problem/P1102
题解代码:

//双指针
#include<bits/stdc++.h>
using namespace std;
const int MAX = 2 * 10e5 + 10;
int n, c, nums[MAX],r=0,rr=0;
int main()
{
	cin >> n >> c;
	for (int i = 0; i < n; i++) cin >> nums[i];
	sort(nums, nums+ n);
	long long cont = 0;
	for (int i = 0; i < n; i++)
	{
		while (r < n && nums[r] - nums[i] <= c) r++;
		while (rr < n && nums[rr] - nums[i] < c) rr++;
	    cont += r - rr;
	}
	cout << cont << endl;
	return 0;
}
//二分
#include<bits/stdc++.h>
using namespace std;
const int MAX = 2 * 10e5 + 10;
int n, c, nums[MAX];
int main()
{
    cin >> n >> c;
    for (int i = 0; i < n; i++) cin >> nums[i];
    sort(nums, nums + n); 
    long long cont = 0;
    for (int i = 0; i < n; i++)
    {
        int l = 0, r = n; 
        while (l + 1 != r)
        {
            int mid = l+(r-l) / 2; 
            if (nums[mid] >= nums[i] + c) r = mid;
            else l = mid;
        }
        int ll = l, rr = r; 
        l = 0, r = n;
        while (l + 1 != r)
        {
            int mid = l+(r-l)/ 2;
            if (nums[mid] >= nums[i] + c + 1) r = mid;
            else l = mid;
        }
        cont += l-ll; 
    }
    cout << cont << endl;
    return 0;
}

posted @ 2024-11-16 01:45  fufuaifufu  阅读(4)  评论(0编辑  收藏  举报