跳到正文

题解

ABC342D题解

Infter约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年2月25日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟

版本

  1. v1当前

题意

  • 给你一长度为 nn 的序列 {ai}\left\{a_i\right\}。

  • 求 ai×aja_i \times a_j 为平方数的无序数对 (i,j)(i, j) 的个数。

思想

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

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

a=p1α1⋅p2α2⋅p2α2⋯pkαka=p_1^{\alpha_1} \cdot p_2^{\alpha_2} \cdot p_2^{\alpha_2} \cdots p_k^{\alpha_k}

考虑什么时候 ai×aja_i \times a_j 为平方数。

若 tt 为平方数,则:

α1≡0mod  2α2≡0mod  2⋮αk≡0mod  2\alpha_1 \equiv 0 \mod 2 \\ \alpha_2 \equiv 0 \mod 2 \\ \vdots \\ \alpha_k \equiv 0 \mod 2

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

α1≡α1′mod  2α2≡α2′mod  2⋮αk≡αk′mod  2\alpha_1 \equiv \alpha'_1 \mod 2 \\ \alpha_2 \equiv \alpha'_2 \mod 2 \\ \vdots \\ \alpha_k \equiv \alpha'_k \mod 2

我们可以给 aia_i 记录下序列 {xi}\left\{x_i\right\} 为 αj≡1mod  2\alpha_j \equiv 1 \mod 2 的 pjp_j。

这样只需要 aia_i 与 aja_j 的 xx 相同相乘即为平方数。

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

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

则 00 乘非 00 的个数为 cnt×(n−cnt)cnt \times (n - cnt)。

00 乘 00 的个数为 cnt×(cnt−1)2\cfrac{cnt \times (cnt - 1)}{2}。

所以答案的贡献先算上 cnt×(n−cnt)+cnt×(cnt−1)2cnt \times (n - cnt) + \cfrac{cnt \times (cnt - 1)}{2}。

我们接着把每一个 aia_i 都计算出他们的 xx,放到 mapmap 里统计同一个 xx 的有多少个。

若这一种的数量为 jj 则对答案的贡献为 j×(j−1)2\cfrac{j \times (j - 1)}{2}。

按照此方法计算即可。

此处 xx 用 vectorvector 记录,因为 vectorvector 可以方便的用 mapmap 统计。

代码

C++
#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;
}
原文