正在载入在线练习界面,本页内容可直接阅读…
AK CSP › CSP-S 2024 第一轮真题 › 第32题
CSP-S 2024 第一轮 第32题:(4分)输入“16”,输出的第二行是?(
题目
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000000 + 5;
const int P1 = 998244353, P2 = 1000000007;
const int B1 = 2, B2 = 31;
const int K1 = 0, K2 = 13;
typedef long long ll;
int n;
bool p[maxn];
int p1[maxn], p2[maxn];
struct H {
int h1, h2, l;
H(bool b = false) {
h1 = b + K1;
h2 = b + K2;
l = 1;
}
H operator + (const H & h) const {
H hh;
hh.l = l + h.l;
hh.h1 = (1ll * h1 * p1[h.l] + h.h1) % P1;
hh.h2 = (1ll * h2 * p2[h.l] + h.h2) % P2;
return hh;
}
bool operator == (const H & h) const {
return l == h.l && h1 == h.h1 && h2 == h.h2;
}
bool operator < (const H & h) const {
if (l != h.l) return l < h.l;
else if (h1 != h.h1) return h1 < h.h1;
else return h2 < h.h2;
}
} h[maxn];
void init() {
memset(p, 1, sizeof(p));
p[0] = p[1] = false;
p1[0] = p2[0] = 1;
for (int i = 1; i <= n; ++i) {
p1[i] = (1ll * B1 * p1[i-1]) % P1;
p2[i] = (1ll * B2 * p2[i-1]) % P2;
if (!p[i]) continue;
for (int j = 2 * i; j <= n; j += i) {
p[j] = false;
}
}
}
int solve() {
for (int i = n; i; --i) {
h[i] = H(p[i]);
if (2 * i + 1 <= n) {
h[i] = h[2 * i] + h[i] + h[2 * i + 1];
} else if (2 * i <= n) {
h[i] = h[2 * i] + h[i];
}
}
cout << h[1].h1 << endl;
sort(h + 1, h + n + 1);
int m = unique(h + 1, h + n + 1) - (h + 1);
return m;
}
int main() {
cin >> n;
init();
cout << solve() << endl;
}本小题
输入 $16$,输出的第二行是?( )
选项
- A. $7$
- B. $9$
- C. $10$
- D. $12$
答案
C
题解
答案是 C.10。
solve() 中先输出 h[1].h1,这是第一行;返回值 m 被 main() 输出,才是题目问的第二行。所以要算的是:h[1] 到 h[16] 去重后有多少种不同的值。
可以把每个 h[i] 理解成一个 01 字符串:
p[i]表示i是否为质数:质数为1,否则为0。+表示拼接字符串。h[i]的拼接顺序是:左孩子的字符串 + 当前节点的值 + 右孩子的字符串,孩子编号分别为2i、2i+1。
不超过 16 的质数是 2、3、5、7、11、13。按代码从后往前计算:
节点 i | h[i] 对应的字符串 |
|---|---|
| 9、10、12、14、15、16 | 0 |
| 11、13 | 1 |
| 8 | 00 |
| 7 | 010 |
| 6 | 001 |
| 5 | 011 |
| 4 | 0000 |
| 3 | 0011010 |
| 2 | 00001011 |
| 1 | 0000101100011010 |
例如: ``text h[4] = h[8] + p[4] + h[9] = "00" + "0" + "0" = "0000" ``
表中每一行是一种不同的字符串,共 10 种。
这里字符串最长为 16,h1 就是其二进制数值,不会发生取模冲突;再加上长度 l,也能区分前导零不同的字符串。因此去重后 m = 10,第二行输出 10。
真题版权归 CCF 所有,本站仅用于非商业教学用途。页面加载后可直接在线作答,作答记录保存在本浏览器或账号中。 京ICP备2026056990号-1
京公网安备11010502062986号