题解:SP20979 UCBINTC - Good
题解:SP20979 UCBINTC - Good
题意简述
给定一个由
思路
使用哈希集合 unordered_set 来优化查找过程,其中:
p:存储已经遍历过的元素q:存储所有两数之和(来自已遍历元素)
对于每个 p,将 p 中所有元素的和加入 q。
代码实现
时间复杂度:
#include<bits/stdc++.h>
using namespace std;
signed main()
{
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
unordered_set<int> p, q;
int cnt = 0;
for (int i = 1; i <= n; i++) {
//检查 a[i] 是否是好元素
for (auto x : p) {
if (q.count(a[i] - x)) {
cnt++;
break;
}
}
//更新数据结构
p.insert(a[i]);
for (auto y : p) {
q.insert(a[i] + y);
}
}
cout << cnt;
return 0;
}