1 条题解
-
0
解题思路
你应该只删除那些找不到另一个元素 ()使得 是 2 的幂的元素。
首先,统计每个值出现的次数。可以使用
map数据结构来实现:对每个元素 ,执行c[a[i]]++。然后,对于每个元素 ,检查它是否存在配对的 。枚举所有可能的和 ,并计算 。如果存在某个 ,使得:
- ,或者
- 且 ,
则说明存在配对的 。
注意:在 C++ 中,使用
map时,最好先检查c.count(s - a[i]),避免使用c[s - a[i]]直接访问不存在的键(这会自动创建一个默认项,增加时间和内存消耗)。最后,统计所有找不到配对的元素数量,即为最少需要删除的元素个数。
C++ 完整代码
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); map<int, int> c; for (int i = 0; i < n; ++i) { cin >> a[i]; c[a[i]]++; } int ans = 0; for (int i = 0; i < n; ++i) { bool ok = false; for (int j = 0; j <= 30; ++j) { int x = (1 << j) - a[i]; if (c.count(x) && (c[x] > 1 || (c[x] == 1 && x != a[i]))) { ok = true; break; } } if (!ok) { ans++; } } cout << ans << '\n'; return 0; }
- 1
信息
- ID
- 6878
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者