結果

問題 No.366 ロボットソート
コンテスト
ユーザー Đức Minh Vũ
提出日時 2026-02-10 17:09:52
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
WA  
実行時間 -
コード長 1,546 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 4,083 ms
コンパイル使用メモリ 353,716 KB
実行使用メモリ 7,972 KB
最終ジャッジ日時 2026-02-10 17:09:57
合計ジャッジ時間 5,285 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 15 WA * 8
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;

    vector<int> a(n);
    for (int i = 0; i < n; i++)
        cin >> a[i];

    vector<int> sorted_all = a;
    sort(sorted_all.begin(), sorted_all.end());

    long long ans = 0;

    for (int start = 0; start < k; start++) {

        vector<int> group;
        vector<int> idx;

        for (int i = start; i < n; i += k) {
            group.push_back(a[i]);
            idx.push_back(i);
        }

        vector<int> sorted_group = group;
        sort(sorted_group.begin(), sorted_group.end());

        // kiểm tra khả thi
        for (int j = 0; j < (int)group.size(); j++) {
            if (sorted_group[j] != sorted_all[idx[j]]) {
                cout << -1;
                return 0;
            }
        }

        // đếm swap để sort group
        int sz = group.size();

        vector<pair<int,int>> arr(sz);
        for (int i = 0; i < sz; i++)
            arr[i] = {group[i], i};

        sort(arr.begin(), arr.end());

        vector<bool> visited(sz, false);

        for (int i = 0; i < sz; i++) {
            if (visited[i] || arr[i].second == i)
                continue;

            int cycle = 0;
            int j = i;

            while (!visited[j]) {
                visited[j] = true;
                j = arr[j].second;
                cycle++;
            }

            if (cycle > 1)
                ans += cycle - 1;
        }
    }

    cout << ans;
}
0