結果

問題 No.270 next_permutation (1)
ユーザー bal4ubal4u
提出日時 2019-08-01 11:11:38
言語 C
(gcc 12.3.0)
結果
AC  
実行時間 8 ms / 2,000 ms
コード長 1,743 bytes
コンパイル時間 304 ms
コンパイル使用メモリ 29,568 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-18 17:19:19
合計ジャッジ時間 1,695 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 0 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 0 ms
4,376 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 0 ms
4,380 KB
testcase_08 AC 0 ms
4,380 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 AC 8 ms
4,376 KB
testcase_11 AC 7 ms
4,376 KB
testcase_12 AC 8 ms
4,380 KB
testcase_13 AC 7 ms
4,376 KB
testcase_14 AC 7 ms
4,376 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.c: 関数 ‘in’ 内:
main.c:9:14: 警告: 関数 ‘getchar_unlocked’ の暗黙的な宣言です [-Wimplicit-function-declaration]
    9 | #define gc() getchar_unlocked()
      |              ^~~~~~~~~~~~~~~~
main.c:14:24: 備考: in expansion of macro ‘gc’
   14 |         int n = 0, c = gc();
      |                        ^~

ソースコード

diff #

// yukicoder: No.270 next_permutation (1)
// 2019.8.1 bal4u

#include <stdio.h>

typedef long long ll;

#if 1
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif
int in() {   // 非負整数の入力
	int n = 0, c = gc();
	//	while (isspace(c)) c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

#define ABS(x)  ((x)>=0?(x):-(x))
int p[100005]; int N;
int b[100005];
ll sum;

void swap(int i, int j) {
	int t;
	sum -= ABS(b[i]-p[i]) + ABS(b[j]-p[j]);
	t = p[i], p[i] = p[j], p[j] = t;
	sum += ABS(b[i]-p[i]) + ABS(b[j]-p[j]);
}

/* algorithm of next_permutation in lexicographic order
    Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
    Find the largest index l greater than k such that a[k] < a[l].
    Swap the value of a[k] with that of a[l].
    Reverse the sequence from a[k + 1] up to and including the final element a[n].
*/
void next_permutation(void) {
	int k, l, r;
	// 右端にある最も長い降順部分列 p[k+1]... p[N-1]をみつける
	k = N-2; while (k >= 0 && p[k] > p[k+1]) k--;
	
	// 上記の降順部分列を昇順列に戻す
	l = k+1, r = N-1;
	while (l < r) swap(l, r), l++, r--;
	
	if (k < 0) return;
	
	//p[k]より大きい要素 p[r]を見つけ、交換する
	r = k+1; while (p[k] > p[r]) r++;
	swap(r, k);
}

int main()
{
	int i, K, f;
	ll ans;

	N = in(), K = in();
	if (K == 0) { puts("0"); return 0; }
	for (i = 0; i < N; i++) p[i] = in();
	sum = 0, f = 0;
	for (i = 0; i < N; i++) {
		b[i] = in(), sum += ABS(b[i]-p[i]);
		if (b[i] < N) f = 1;
	}
	if (f) {
		ans = 0;
		while (K--) ans += sum, next_permutation();
		printf("%lld\n", ans);
	} else printf("%lld\n", sum*K);
	return 0;
}
0