結果

問題 No.366 ロボットソート
ユーザー startcppstartcpp
提出日時 2016-04-30 00:14:41
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,751 bytes
コンパイル時間 624 ms
コンパイル使用メモリ 67,520 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-15 07:49:05
合計ジャッジ時間 1,457 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

/*
8 6 5 3 1 10
->分解(a[i], a[i+k], a[i+2k], …と選んでグループiを作る)->
8 5 1
6 3 10
同じ行の数字同士で交換になる。
-> 各グループで交換回数を独立に最小化すればよい。
グループ内では操作が隣り合った2要素を交換になる。
-> 反転数を考えると、バブルソートが最善!

最初から昇順なら、分解不可だが、-1ではなく0を出力!
n % k != 0のときは、分解不可
a[i + m * k]の整列後の場所がa[i + p * k]で表せないときは、交換不可
(m, pは任意の整数。mを最初に固定)
それ以外は、分解可能
O(N^2/K) … 計算量が最高に面白いです!
*/

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

int n, k;
int a[100000];

bool isNg() {
	int sortedA[1000];
	
	if (n % k != 0) return true;
	for (int i = 0; i < n; i++) sortedA[i] = a[i];
	sort(sortedA, sortedA + n);
	
	for (int i = 0; i < n; i++) {
		int pos = lower_bound(sortedA, sortedA + n, a[i]) - sortedA;
		if (pos % k != i % k) return true;
	}
	return false;
}

int bubbleSort(vector<int> a) {
	int i, j, cnt = 0;
	
	for (i = 0; i < a.size() - 1; i++) {
		for (j = a.size() - 1; j > i; j--) {
			if (a[j-1] > a[j]) {
				cnt++;
				swap(a[j-1], a[j]);
			}
		}
	}
	return cnt;
}

int main() {
	int i, j;
	
	cin >> n >> k;
	for (i = 0; i < n; i++) cin >> a[i];
	for (i = 0; i < n - 1; i++) if (a[i] > a[i+1]) break; if (i == n - 1) { cout << 0 << endl; return 0; }
	if (isNg()) { cout << -1 << endl; return 0; }
	
	vector<int> arrays[1000];
	for (i = 0; i < n; i++) arrays[i % k].push_back(a[i]);
	
	int ans = 0;
	for (i = 0; i < k; i++) {
		ans += bubbleSort(arrays[i]);
	}
	cout << ans << endl;
	return 0;
}
0