CF131B Opposites Attract 题解
Content
有一个长度为 \(n\) 的数列,要求选出一个二元组 \((i,j)\) 使得满足 \(a_i+a_j=0\) 且 \(i<j\)。
数据范围:\(1\leqslant n\leqslant 10^5,|a_i|\leqslant10\)。
Solution
这题目,即使 \(a_i\) 的规模开到 \(10^6\) 的绝对值以内也不算问题,因为我们有桶。
但是,谁能奈何 \(a_i\) 如此小的范围?因此空间就占得很小了。
也许你会说,\(a_i\) 会是负数,但是我们可以转化一下,把它变成正数不就行了?于是,根据数据范围,我们给所有数都加上 \(10\)。然后,看 \(a_i\) 前面有多少个 \(a_j=-a_i\)(即满足 \(a_i+a_j=0\)),答案就加上几。
请注意,这题目要开 \(\texttt{long long}\),不然会 \(\texttt{WA}\) 掉一些点。
Code
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;
int n, a[100007];
long long ans, k[37];
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
ans += k[-a[i] + 10];
k[a[i] + 10]++;
}
printf("%lld", ans);
return 0;
}