跳到正文

个人记录

T711542 数对查找

clki约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月24日
更新
2025年12月24日
篇幅
约 1 分钟

版本

  1. v1当前

先读题:

给出一串正整数数列以及一个正整数 C,要求计算出所有满足 A−B=C 的数对的个数(不同位置的数字一样的数对算不同的数对)。

给定一个数组和一个数字C

求a[i] - a[j] == c

可以用二分实现

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5 + 10;
int n,a[N],m;
signed main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++)cin>>a[i];
    sort(a + 1,a + 1 + n);
	int cnt = 0;
		for(int i=1;i<=n;i++){
            int x = a[i] -  m;
		int pos = lower_bound(a + 1,a + 1 + n,x)- a;
		int net = upper_bound(a + 1,a + 1 + n,x)- a - 1;
	    if(pos != n + 1 && a[pos] == x){
            cnt += net - pos + 1;
        }
	}
	cout<<cnt;
	return 0;
}
原文