洛谷 P1102 AB 数对

题目描述

出题是一件痛苦的事情!

相同的题目看多了也会有审美疲劳,于是我舍弃了大家所熟悉的 A+B Problem,改用 A-B 了哈哈!

好吧,题目是这样的:给出一串数以及一个数字 CC,要求计算出所有 A - B = CAB=C 的数对的个数(不同位置的数字一样的数对算不同的数对)。

输入格式

输入共两行。

第一行,两个整数 N, CN,C。

第二行,NN 个整数,作为要求处理的那串数。

输出格式

一行,表示该串数中包含的满足 A - B = CAB=C 的数对的个数。

输入输出样例

输入 #1

4 1
1 1 2 3

输出 #1

3

分析

考点为找一串数中某一个数出现的次数,因为数据过大不能直接用桶,所以可以用map这个proplus大桶,也可以直接上lower_bound和upper_bound


代码

#include<bits/stdc++.h>
#define int long long
using namespace std;

map <long long,long long> num;
long long a[200005];
long long ans;

signed main()
{
    int n,c;
    cin>>n>>c;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        num[a[i]]++;
    }
    for(int i=1;i<=n;i++)
    {
        ans+=num[a[i]+c];
    }
    cout<<ans<<endl;
    return 0; 
}
#include<bits/stdc++.h>
#define int long long
using namespace std;

int num[2000005];
int ans;

signed main()
{
    int n,c;
    cin>>n>>c;
    for(int i=1;i<=n;i++)
    {
        cin>>num[i];
    }
    sort(num+1,num+n+1);
    for(int i=1;i<=n;i++)
    {
        int a=num[i]+c;//2 3 3 3 情况 upper返回的是end(),依然成立 
        if(lower_bound(num+1,num+n+1,a)==upper_bound(num+1,num+n+1,a))//大于等于的结果和大于的结果一样,不存在
        continue;//多余的一步,方便理解  
        ans+=upper_bound(num+1,num+n+1,a)-lower_bound(num+1,num+n+1,a);
    }
    cout<<ans<<endl;
    return 0; 
}

/*我们再来举一个例子,来表现upper_bound和lower_bound的好处:
题意:给你n个数字(n<=200000),再给你一个数字m,让你输出数字m在n个数字中出现的次数。

这道题完全可以使用upper_bound+lower_bound实现,
我们只需要将upper_bound返回的迭代器和lower_bound返回的迭代器相减的绝对值就可以了。*/

 

原文地址:https://www.cnblogs.com/KyleDeng/p/15561634.html