lower_bound与upper_bound

洛谷P1102

一句话题意:给一串数和正整数 \(C\) ,求串中 \(A - B = C\) 的数对个数

做法:排序,对每个 \(a_i\) ,找upper_bound - lower_bound即是 \(a_i - C\) 的个数

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, c, a[N];
int main(){
	scanf("%d%d", &n, &c);
	for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
	sort(a + 1, a + n + 1);
	long long ans = 0;
	for(int i = 1; i <= n; ++i) ans += (upper_bound(a + 1, a + n + 1, a[i] + c) - a - (lower_bound(a + 1, a + n + 1, a[i] + c) - a));
	cout << ans;
	return 0;
}

posted @ 2022-04-09 09:52  Faker_yu  阅读(53)  评论(1)    收藏  举报