map映射巧用 A-B Problems

 

A-B problem


Description

  大家都非常熟悉 A+B Problem! 题目看多了也有审美疲劳,于是我舍弃了,改用 A-B problem! 题目是这样的:给出一串数以及一个数字 C,要求计算出所有 A-B=C 的数对 的个数。( 注意: 不同位置的数字一样的数对算不同的数对)
Input Format

  第一行包括 2 个非负整数 N 和 C,中间用空格隔开。 第二行有 N 个整数,中间用空格隔开,作为要求处理的那串数。
Output Format

  输出一行,表示该串数中包含的所有满足 A-B=C 的数对的个数。
Sample Input
4 1
1 1 2 3
Sample Output
3
Data Limit

  对于 50%的数据, N <= 2000; 对于 100%的数据, N <= 200000。

#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
int main()
{
    int n;
    ll c;
    scanf("%d%lld",&n,&c);
    ll cnt[222222];
    map<ll,int>mm;
    for(int i=0;i<n;i++)
    {
        scanf("%lld",&cnt[i]);
        mm[cnt[i]]++;
    }
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        if(c!=0)
            ans+=mm[cnt[i]+c];
        if(c==0)
            ans+=mm[cnt[i]+c]-1;
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42060896/article/details/81668530
A-B