結果

問題 No.366 ロボットソート
ユーザー bal4ubal4u
提出日時 2019-07-06 16:29:15
言語 C
(gcc 12.3.0)
結果
AC  
実行時間 1 ms / 2,000 ms
コード長 1,592 bytes
コンパイル時間 831 ms
コンパイル使用メモリ 31,372 KB
実行使用メモリ 4,348 KB
最終ジャッジ日時 2023-10-26 01:51:08
合計ジャッジ時間 1,845 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 1 ms
4,348 KB
testcase_03 AC 1 ms
4,348 KB
testcase_04 AC 1 ms
4,348 KB
testcase_05 AC 1 ms
4,348 KB
testcase_06 AC 1 ms
4,348 KB
testcase_07 AC 1 ms
4,348 KB
testcase_08 AC 1 ms
4,348 KB
testcase_09 AC 1 ms
4,348 KB
testcase_10 AC 1 ms
4,348 KB
testcase_11 AC 1 ms
4,348 KB
testcase_12 AC 1 ms
4,348 KB
testcase_13 AC 1 ms
4,348 KB
testcase_14 AC 1 ms
4,348 KB
testcase_15 AC 0 ms
4,348 KB
testcase_16 AC 1 ms
4,348 KB
testcase_17 AC 1 ms
4,348 KB
testcase_18 AC 1 ms
4,348 KB
testcase_19 AC 1 ms
4,348 KB
testcase_20 AC 1 ms
4,348 KB
testcase_21 AC 1 ms
4,348 KB
testcase_22 AC 1 ms
4,348 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.c: In function 'in':
main.c:9:14: warning: implicit declaration of function 'getchar_unlocked' [-Wimplicit-function-declaration]
    9 | #define gc() getchar_unlocked()
      |              ^~~~~~~~~~~~~~~~
main.c:15:24: note: in expansion of macro 'gc'
   15 |         int n = 0, c = gc();
      |                        ^~

ソースコード

diff #

// yukicoder: No.366 ロボットソート
// 2019.7.6 bal4u

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if 1
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

#define INF   0x7f7f7f7f
int a[1005], w[1005];
int number_of_inversions(int low, int high) { 
	int i, j, k, p, mid;
	int ans = 0;

	if (low < high) {
		mid = (low + high) >> 1;
		ans += number_of_inversions(low,   mid);
		ans += number_of_inversions(mid+1, high);
		p = mid-low+1;
		memcpy(w, a+low, sizeof(int)*p), w[p] = INF;
		k = low, j = 0, i = mid+1;

		while (i <= high) {
			if (w[j] <= a[i]) a[k++] = w[j++];
			else ans += i-k,  a[k++] = a[i++];
		}
		memcpy(a+k, w+j, sizeof(int)*(p-j));
	}
	return ans;
}

typedef struct { int a, id; } T;
T t[1005]; int N, K;
int A[1005];

int cmp(const void *a, const void *b) { return ((T *)a)->a - ((T *)b)->a; }

int main()
{
	int i, j, k, f, ans;

	N = in(), K = in();
	
	if (K == 1) {
		for (i = 0; i < N; i++) a[i] = in();
		printf("%d\n", number_of_inversions(0, N-1));
		return 0;
	}
		
	f = 0; for (i = 0; i < N; i++) {
		t[i].a = A[i] = in(), t[i].id = i;
		if (i && t[i-1].a > t[i].a) f = 1;
	}
	if (!f) { puts("0"); return 0; }
	
	qsort(t, N, sizeof(T), cmp);
	for (i = 0; i < N; i++) {
		if ((t[i].id - i) % K) { puts("-1"); return 0; }
	}
	
	ans = 0;
	for (i = 0; i < K; i++) {
		k = 0; for (j = i; j < N; j += K) a[k++] = A[j];
		ans += number_of_inversions(0, k-1);
	}
	printf("%d\n", ans);
	return 0;
}
0