P1102 A-B 数对(加深对lower_bound 和upper_bound的理解)

传送门

直接暴力,两个for循环, 2 ∗ 1 0 5 2*10^5 2105爆炸
2021/3/20
疑问:ans += ((upper_bound(a+1,a+n+1,a[i]+c)-a)-(lower_bound(a+1,a+n+1,a[i]+c)-a));
c = 1
假设1 1 2 2 3
那么对于第一个1来说有两个2成立,用上式来套,成立吗?这需要深层次来理解lower_bound() 和upper_bound()

点击理解

//#include<bits/stdc++.h>
#include <stdio.h>
#include <iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#define ll long long
#define ios ios::sync_with_stdio(false);cin.tie(0)
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define fep(i,a,b) for(int i=b;i>=a;--i)
#define scf(x) scanf("%lld",&x)
#define prf(x) printf("%lld\n",x)
#define deprf(x) printf("[%lld]\n",x)
#define mem(x,y) memset(x,y,sizeof(x))
#define inf 2147483647
const int mod=1e9+7;
const int maxn=1e6+7;
using namespace std;
ll a[maxn];

int read(){//快读
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}



int main()
{
    ios;
    ll n=read(),c=read();
    rep(i,1,n){
        a[i] = read();
    }
    sort(a+1,a+n+1);
    ll ans =0;
    rep(i,1,n){
        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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值