1. 程式人生 > 實用技巧 >P1102 A-B 數對【map】

P1102 A-B 數對【map】

題目

https://www.luogu.com.cn/problem/P1102

思路

使用一個map記錄一樣的數字出現的次數,使用另外一個map記錄數字來尋找比自己大c和小c的數字

7 10 與10 7都算,最後整體除以2就行

程式碼

#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
map<long long , long long>list;
map<long long, long long>amount;
int main()
{
    long
long n, c; long long counts = 0; scanf("%lld%lld", &n, &c); for (int i = 1; i <=n; i++) { long long a; scanf("%lld", &a); list[a] = i; amount[a]++; } map<long long, long long>::iterator it = amount.begin(); for (; it != amount.end(); it++) {
if (list[it->first + c] != 0)counts += amount[it->first + c] * amount[it->first]; if (list[it->first - c] != 0)counts += amount[it->first - c] * amount[it->first]; } printf("%lld", counts/2); }