結果

問題 No.366 ロボットソート
ユーザー mamekinmamekin
提出日時 2016-04-30 16:40:22
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 2,004 bytes
コンパイル時間 1,402 ms
コンパイル使用メモリ 116,344 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-28 15:14:11
合計ジャッジ時間 2,008 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 2 ms
4,376 KB
testcase_11 AC 2 ms
4,380 KB
testcase_12 AC 2 ms
4,380 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 2 ms
4,380 KB
testcase_15 AC 2 ms
4,380 KB
testcase_16 AC 1 ms
4,376 KB
testcase_17 AC 2 ms
4,380 KB
testcase_18 AC 2 ms
4,376 KB
testcase_19 AC 2 ms
4,376 KB
testcase_20 AC 2 ms
4,376 KB
testcase_21 AC 2 ms
4,376 KB
testcase_22 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
using namespace std;

// Binary Indexed Tree
class BinaryIndexedTree
{
private:
    int n;
    vector<int> data;
public:
    BinaryIndexedTree(int n){ // コンストラクタ
        this->n = n;
        data.assign(n+1, 0);
    }
    void add(int k, int x){ // k番目の要素にxを加算する
        ++ k;
        while(k <= n){
            data[k] += x;
            k += k & -k;
        }
    }
    int sum(int k){ // 区間[0,k]の総和を返す
        ++ k;
        int ret = 0;
        while(k > 0){
            ret += data[k];
            k -= k & -k;
        }
        return ret;
    }
    int sum(int a, int b){ // 区間[a,b]の総和を返す
        return sum(b) - sum(a-1);
    }
};

int inversionNumber(const vector<int>& v)
{
    int n = v.size();
    vector<pair<int, int> > p(n);
    for(int i=0; i<n; ++i)
        p[i] = make_pair(v[i], i);
    sort(p.rbegin(), p.rend());

    BinaryIndexedTree bit(n);
    int ans = 0;
    for(int i=0; i<n; ++i){
        ans += bit.sum(p[i].second);
        bit.add(p[i].second, 1);
    }
    return ans;
}

int main()
{
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    vector<vector<int> > v(k);
    for(int i=0; i<n; ++i){
        cin >> a[i];
        v[i%k].push_back(a[i]);
    }
    sort(a.begin(), a.end());

    int ans = 0;
    for(int i=0; i<k; ++i){
        ans += inversionNumber(v[i]);
        sort(v[i].begin(), v[i].end());
    }

    vector<int> x;
    for(int i=0; i<n; ++i)
        x.push_back(v[i%k][i/k]);

    if(x == a)
        cout << ans << endl;
    else
        cout << -1 << endl;

    return 0;
}
0