CF1005C题解修改版
small_Dongpo · · 题解
不知为什么我不能修改题解。
CF1005C 题解
思路
这道题题解许多人都用 map 做,也有人用 multiset 做,不过是
不会 set 的请看:https://www.luogu.com.cn/article/ij9oqloa
注:如果我没在下方特意写,那么multiset 和 set 在此函数上功能完全一样
首先,我们定义 multiset, 一个叫 ms,表示已经配对过的数。
为了更好地理解,我们拿样例
-
第
1 个数4 ,是单身狗,把它存进s 里。 -
第
2 个数7 ,我们可以枚举来看它是否能和别的数配对,由于2^{10} ≈ 10^3 且a_i ≤ 10^9 可以知道a_i ≤ 2^{30} ,我们枚举j 从0 到30 ,如果2^j ≥ 7 且s 里有2^j - 7 则将7 和2^j - 7 放到ms 中,但并未有数与7 配对,所以把7 放到s 中。 -
第
3 个数1 经枚举可发现当j = 8 时,\operatorname{pow}(2, j) - 7 恰好等于7 ,把7 取出,与1 都放入ms 中。
……
直到第
然后,我们就会特别轻松地写出代码:
#include <iostream>
#include <set>
#include <cmath>
using namespace std;
typedef long long l;
multiset<l> s, ms;
int main() {
l n;
scanf("%lld", &n);
for (l i = 1; i <= n; ++i) {
l x;
bool f = 0;
scanf("%lld", &x);
for (l j = 0; j <= 30; ++j) {
if (pow(2, j) >= x) {
l y = pow(2, j) - x;
if (ms.count(y) && f == 0) {
ms.insert(x);
f = 1;
}
if (s.count(y)) {
if (f == 0) ms.insert(x);
for (l j = 1; j <= s.count(y); ++j) ms.insert(y);
s.erase(y);
f = 1;
}
}
}
if (f == 0) s.insert(x);
}
cout << n - ms.size();
return 0;
}
然后评测:
当我们十分惊喜的时候却画面一转:
于是用一个变量
代码
#include <iostream>
#include <set> // multiset是用set库,并没有multiset库
#include <cmath> // 要用pow,别把cmath库落下
using namespace std;
typedef long long l;
l n, cnt = 0, x;
multiset<l> s, ms;
int main() {
scanf("%lld", &n);
for (l i = 1; i <= n; ++i) {
bool f = 0; // f用来标记是否已将x存入ms
scanf("%lld", &x);
if (ms.count(x)) { // 如果ms中已经有x,说明x不是单身狗,直接把重复元素个数加1就行了
cnt++;
continue;
}
for (l j = 0; j <= 30; ++j) { // j是从0开始,不是从1开始
if (pow(2, j) >= x) {
l y = pow(2, j) - x;
if (ms.count(y) && f == 0) { // 如果f是1,两个都存了,没必要再存了
ms.insert(x);
f = 1;
}
if (s.count(y)) {
if (f == 0) ms.insert(x); // 如果已经存入,就不用再存了
ms.insert(y);
cnt += s.count(y) - 1; // 一定要减1,y在因为ms里面已经算了一遍了
s.erase(y); // 记得要删掉,不然以后再遇到就重复了
f = 1;
}
}
}
if (f == 0) s.insert(x);
}
cout << n - ms.size() - cnt; // 注意问的不是已配对的
return 0;
}
编写于2023.8.3.
更改于2024.2.8.,把一些代码框改成了