b451困難

交錯位置的互質對

運用奇偶位置的 Möbius 互質計數,正確求解本題並處理邊界情況。

解題思路

把奇數位置與偶數位置的值分別計頻率。

對每個 d,累計兩邊可被 d 整除的值數量 O[d]、E[d];由互質指示式 Σ_{d|gcd}μ(d),答案為 Σ μ(d)O[d]E[d]。

一奇一偶的位置對恰好由兩邊各取一次,不需除二;用線性篩求 μ 並按倍數累加頻率。

設 V=max a,時間 O(V log V+N),空間 O(V+N)。

Step-by-step animation

教學例子:6、5、10、7、3 的奇位置值為6、10、3,偶位置值5、7。

回報動畫錯誤
步驟 1 / 3

步驟 1

6、5、10、7、3 的奇位置值為6、10、3,偶位置值5、7。

6,10,3
5,7
狀態
共6個跨組對

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n);
    int V = 1;
    for (auto &x : a) {
        cin >> x;
        V = max(V, x);
    }
    vector<int> o(V + 1), e(V + 1), mu(V + 1), lp(V + 1), pr;
    for (int i = 0; i < n; i++)
        (i % 2 ? e : o)[a[i]]++;
    mu[1] = 1;
    for (int i = 2; i <= V; i++) {
        if (!lp[i]) {
            lp[i] = i;
            mu[i] = -1;
            pr.push_back(i);
        }
        for (int p : pr) {
            if (1LL * i * p > V)
                break;
            lp[i * p] = p;
            if (i % p == 0) {
                mu[i * p] = 0;
                break;
            }
            mu[i * p] = -mu[i];
        }
    }
    long long ans = 0;
    for (int d = 1; d <= V; d++)
        if (mu[d]) {
            long long x = 0, y = 0;
            for (int j = d; j <= V; j += d) {
                x += o[j];
                y += e[j];
            }
            ans += mu[d] * x * y;
        }
    cout << ans << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多