3.20总结
Wonderful_Anser · · 个人记录
比赛情况
| P7071 优秀的拆分 | P1461 海明码 | P13591 Kitchen Timer | P11485 Non-breath Oblige | P10307 「Cfz Round 2」Binary | 总分 |
|---|---|---|---|---|---|
| 192pts |
题目
P7071 [CSP-J 2020] 优秀的拆分
题意
题目要求将正整数
思路
1. 奇偶性判断
所有 -1。
2. 偶数情况的拆分
当
-
6_{10} = 110_2 = 4 + 2 -
14_{10} = 1110_2 = 8 + 4 + 2
由于
3. 贪心策略
从大到小枚举
- 从
2^{30} 开始向下检查(因为n \le 10^7 < 2^{30} ) - 如果当前幂
2^i \le n ,则选择它,并从n 中减去 - 继续检查更小的幂
这样得到的拆分方案是从大到小排列的,且是唯一的。
代码实现
#include <bits/stdc++.h>
using namespace std;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
// 奇数无解
if (n % 2 != 0)
{
cout << "-1";
return 0;
}
// 从大到小枚举 2 的幂
for (int i = 30; i >= 1; i--)
{
if ((1 << i) <= n)
{
n -= (1 << i);
cout << (1 << i) << " ";
}
}
return 0;
}
时间复杂度
循环固定 30 次,时间复杂度
样例验证
| 输入 | 输出 | 说明 |
|---|---|---|
| 6 | 4 2 | |
| 7 | -1 | 奇数,无解 |
| 126 | 64 32 16 8 4 2 |
P1461 [USACO2.1] 海明码 Hamming Codes
题意
题目要求找出
需要输出字典序最小的解,即把编码看成二进制数转成十进制后,从小到大输出,每行最多 10 个数。
思路
1. 数据范围
-
n \le 64 -
b \le 8$,因此编码范围是 $0$ 到 $2^b - 1$,最大为 $255 -
d \le 7
由于搜索空间很小(最多 256 个数),可以采用贪心。
2. 贪心策略
从 0 开始,从小到大依次检查每个数:
- 如果当前数与已经选中的每个数的海明距离都
\ge d ,就把它加入答案 - 否则跳过
这样得到的集合一定是字典序最小的,因为我们是按数值从小到大尝试的。
3. 海明距离计算
两个数
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, b, d, cnt, a[105];
// 检查两数海明距离是否 >= d
bool hm(int a, int b)
{
int cnt = 0;
for (int i = 60; i >= 0; i--)
{
int t1 = (a >> i) & 1;
int t2 = (b >> i) & 1;
if (t1 != t2)
cnt++;
}
return cnt >= d;
}
signed main()
{
cin >> n >> b >> d;
a[++cnt] = 0; // 0必选
int o = pow(2, b) - 1; // b位最大值
for (int i = 1; i <= o; i++)
{
bool v = 0;
for (int j = 1; j <= cnt; j++)
if (hm(i, a[j]) == 0)
{
v = 1;
break;
}
if (v == 0)
a[++cnt] = i;
if (cnt == n)
break;
}
for (int i = 1; i <= n; i++)
{
cout << a[i] << " ";
if (i % 10 == 0)
cout << "\n";
}
return 0;
}
P11485 「Cfz Round 5」Non-breath Oblige 题解
题意
每次操作可以把
-
x < 2^n -
s \lor x = 2^n - 1 - 代价为
s \oplus x
求
分类讨论
设
1. s = t
不需要操作,代价为0。
2. n = 1
只有0和1两个数,只能互相变,代价固定为1。
3. s + t = F
此时
4. s \lor t = F
可以直接一步从
5. 其他情况
无法一步到位,最优路径是先从
代码
#include <bits/stdc++.h>
using namespace std;
long long T, n, s, t;
int main()
{
cin >> T;
while (T--)
{
cin >> n >> s >> t;
if (s == t) // 第一种情况
{
cout << "0\n";
} else
{
if (n == 1) // 第二种情况
{
cout << "1\n";
} else
{
if (s + t == (1LL << n) - 1) // 第三种情况
{
cout << (s ^ t) << "\n";
} else
{
if ((s | t) != (1LL << n) - 1) // 第四种情况
{
cout << (s ^ ((1LL << n) - 1)) + (((1LL << n) - 1) ^ t) << "\n";
} else // 其他情况
{
cout << (s ^ t) << "\n";
}
}
}
}
}
return 0;
}