ABC342D题解

· · 题解

题意

思想

如果直接按照题意模拟复杂度高达 \mathcal{O}(n^2\sqrt{a}),会 TLE。

根据算数基本定理,我们将 a_i 分解。

a=p_1^{\alpha_1} \cdot p_2^{\alpha_2} \cdot p_2^{\alpha_2} \cdots p_k^{\alpha_k}

考虑什么时候 a_i \times a_j 为平方数。

若 t 为平方数,则:

\alpha_1 \equiv 0 \mod 2 \\ \alpha_2 \equiv 0 \mod 2 \\ \vdots \\ \alpha_k \equiv 0 \mod 2

此时要让他为平方数则要求:

\alpha_1 \equiv \alpha'_1 \mod 2 \\ \alpha_2 \equiv \alpha'_2 \mod 2 \\ \vdots \\ \alpha_k \equiv \alpha'_k \mod 2

我们可以给 a_i 记录下序列 \left\{x_i\right\} 为 \alpha_j \equiv 1 \mod 2 的 p_j。

这样只需要 a_i 与 a_j 的 x 相同相乘即为平方数。

但是这里有个特例:0 乘任何数都等于 0,为平方数。

所以我们先把 0 处理掉,设 0 的个数为 cnt。

则 0 乘非 0 的个数为 cnt \times (n - cnt)。

所以答案的贡献先算上 $cnt \times (n - cnt) + \cfrac{cnt \times (cnt - 1)}{2}$。 我们接着把每一个 $a_i$ 都计算出他们的 $x$,放到 $map$ 里统计同一个 $x$ 的有多少个。 若这一种的数量为 $j$ 则对答案的贡献为 $\cfrac{j \times (j - 1)}{2}$。 按照此方法计算即可。 此处 $x$ 用 $vector$ 记录,因为 $vector$ 可以方便的用 $map$ 统计。 ## 代码 ```cpp #include <bits/stdc++.h> using namespace std; #define int long long constexpr int MAXN = 2e5 + 5; int n; int a[MAXN]; map<vector<int>, int> mp; void build(int x) { vector<int> ans; map<int, int> tmp; for (int i = 2; i * i <= x; i++) { if (x % i == 0) { while (x % i == 0) { x /= i; tmp[i]++; } } } if (x > 1) { tmp[x]++; } for (auto [i, j] : tmp) { if ((j & 1) == 0) continue; ans.push_back(i); } mp[ans]++; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; long long ans = 0; long long cnt = 0; for (int i = 1; i <= n; i++) { cin >> a[i]; if (a[i] == 0) cnt++; else build(a[i]); } ans += cnt * (n - cnt) + cnt * (cnt - 1) / 2; for (auto [i, j] : mp) { ans += 1ll * j * (j - 1) / 2; } cout << ans << endl; return 0; } ```