結果

問題 No.270 next_permutation (1)
ユーザー bal4u
提出日時 2019-08-01 11:11:38
言語 C
(gcc 13.3.0)
結果
AC  
実行時間 7 ms / 2,000 ms
コード長 1,743 bytes
コンパイル時間 237 ms
コンパイル使用メモリ 30,720 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-07-05 07:27:00
合計ジャッジ時間 1,157 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 15
権限があれば一括ダウンロードができます
コンパイルメッセージ
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:14:24: note: 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;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0