b771簡單

裁剪平方誤差的環對齊

逐位移排序平方誤差,只計位移而不計捨棄方式。

解題思路

對每個 s,逐 i 計算 (A[i]-B[(i+s)%N])² 並排序。捨去 K 個最大值等價於取最小 N-K 個相加;排序後相同誤差的先後不影響成本,因此不需要枚舉哪些相等項被捨去。

將 N 個位移的成本逐一比較,較小時重設最佳位移數,同值則加一。位移從0遞增,所以第一個達到目前最小成本的 s 就是最小代表;即使 B 本身有週期,不同 s 仍分別計數。

時間 O(N² log N),空間 O(N),Python 輸入 buffer O(N);N≤120,單項平方≤4·10^12、總成本≤4.8·10^14,使用64位。

Step-by-step animation

逐步推演(例子條件見步驟說明)

回報動畫錯誤
步驟 1 / 3

位移0

自訂 A=[1,2],B=[2,1],K=1,誤差[1,1],保留一個得1。

1
1
成本
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n, K;
    cin >> n >> K;
    vector<ll> a(n), b(n);
    for (ll &x : a)
        cin >> x;
    for (ll &x : b)
        cin >> x;
    ll best = LLONG_MAX;
    int cnt = 0, bs = 0;
    for (int s = 0; s < n; s++) {
        vector<ll> e;
        for (int i = 0; i < n; i++) {
            ll d = a[i] - b[(i + s) % n];
            e.push_back(d * d);
        }
        sort(e.begin(), e.end());
        ll v = accumulate(e.begin(), e.begin() + n - K, 0LL);
        if (v < best)
            best = v, cnt = 1, bs = s;
        else if (v == best)
            cnt++;
    }
    cout << best << ' ' << cnt << ' ' << bs << '\n';
}

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

更多