h_nosonの日記

競プロ、CTFなど

yukicoder No.366 ロボットソート

問題
No.366 ロボットソート - yukicoder
N個の数字a_iが並べられていて,
a_ia_{i+K}(i{<}N-K)の数字を入れ替えることができる.
昇順に並べ替えられる時はその操作回数を
並べ替えられない時は-1を出力するという問題.

解法
添字iに対してi\text{ mod }kが等しくなる集合に分ける.
それぞれをバブルソートし,操作回数を数える.
ソートした結果が全体としてソートされているものであればその操作回数を
ソートされていなければ-1を出力する.

ソースコード

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

#define RREP(i,s,e) for (i = s; i >= e; i--)
#define rrep(i,n) RREP(i,n-1,0)
#define REP(i,s,e) for (i = s; i < e; i++)
#define rep(i,n) REP(i,0,n)
#define INF 100000000

typedef long long ll;

int main() {
    int i, j, l, n, k, ans;
    int a[1000];
    cin >> n >> k;
    rep (i,n) cin >> a[i];
    ans = 0;
    rep (i,k) {
        int mx = 0;
        for (j = i; j < n; j+=k) {
            for (l = (n-1-i)/k*k+i; l > j; l-=k) {
                if (a[l] < a[l-k]) {
                    swap(a[l],a[l-k]);
                    ans++;
                }
            }
        }
    }
    bool ok = true;
    rep (i,n-1)
        ok &= a[i] < a[i+1];
    if (ok)
        cout << ans << endl;
    else 
        cout << -1 << endl;
    return 0;
}