题解:P10063 [SNOI2024] 平方数

· · 题解

都去听 IF!

非常神秘的人类智慧题。

如果值域不大,可以对每个数做素因子分解,那就要求区间内每个素数必须出现偶数次,做异或和哈希即可。

但出题人目的明确地将值域开到了 10^{36},这样上面的做法就死了。

平方数考虑变成二次剩余,找一个大素数 p,要求和每个 a_i 都互素。由于二次剩余与非二次剩余之间的乘法很像异或,故考虑判断每一个数是否是二次剩余,是的话就给该位置赋值成 0,否则赋值成 1。这样一个区间合法的必要条件就是区间异或和为 0,需要多做个几遍,时间复杂度为 \mathcal O(Tn\log V),大概是过不去的。

要把这个 \log V 干掉,唯一的方法就是 \mathcal O(p) 预处理出所有二次剩余,这样 p 不能开得太大,不好保证和所有的 a_i 均互素,不过没关系,直接把所有的 p 因子除干净也是一样的,这样复杂度就是 \mathcal O(Tn),T 可以开到 64,正确性还是可以的。

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef __int128 lll;
const int N = 300005, V = 5e6, K = 1e5;
int n; ull b[N], ans; lll a[N], x; bool flg[V]; mt19937 rnd(time(0)); unordered_map<ull, basic_string<int> > mp;
lll read() { lll x = 0; char c = '%'; while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 - '0' + c, c = getchar(); return x; }
bool isp(int x) { if (x <= 1) return 0; for (int i = 2; i * i <= x; i++) if (!(x % i)) return 0; return 1; }
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) a[i] = read();
    for (int t = 0, p; t < 64; t++) {
        p = 0; while (!isp(p)) p = rnd() % V + 1;
        memset(flg, 0, sizeof(flg)); for (int i = 1; i < p; i++) flg[(ull)i * i % p] = 1;
        for (int i = 1; i <= n; i++) {
            x = a[i]; while (!(x % p)) x /= p;
            if (!flg[x % p]) b[i] |= 1ull << t;
        }
    }
    mp[0].push_back(0);
    for (int i = 1; i <= n; i++) b[i] ^= b[i - 1], ans += mp[b[i]].size(), mp[b[i]].push_back(i);
    printf("%llu\n", ans), ans = 0;
    for (int i = 0; i < n && ans < K; i++) {
        for (int j : mp[b[i]]) if (j > i) { printf("%d %d\n", i + 1, j), ans++; if (ans >= K) break; }
    }
}