結果
| 問題 |
No.270 next_permutation (1)
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2017-06-05 16:16:05 |
| 言語 | D (dmd 2.109.1) |
| 結果 |
AC
|
| 実行時間 | 57 ms / 2,000 ms |
| コード長 | 979 bytes |
| コンパイル時間 | 1,654 ms |
| コンパイル使用メモリ | 151,168 KB |
| 実行使用メモリ | 7,756 KB |
| 最終ジャッジ日時 | 2024-06-12 19:44:30 |
| 合計ジャッジ時間 | 2,882 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 15 |
ソースコード
import std.algorithm, std.conv, std.range, std.stdio, std.string;
import std.math; // math functions
void main()
{
auto rd = readln.split.to!(size_t[]), n = rd[0], k = rd[1];
auto pi = readln.split.to!(long[]);
auto bi = readln.split.to!(long[]);
if (k == 0) {
writeln(0);
return;
}
auto l = dist(pi, bi), r = l;
auto changeDigits(long[] pi)
{
foreach_reverse (i; 0..n-1)
if (pi[i] < pi[i+1])
return n-i-1;
return n;
}
foreach (_; 0..k-1) {
auto d = changeDigits(pi);
if (d == n) {
pi.reverse();
l = dist(pi, bi);
} else {
l -= dist(pi[$-d-1..$], bi[$-d-1..$]);
auto qi = pi[$-d..$];
qi.reverse();
auto c = pi[$-d-1];
auto e = qi.assumeSorted.upperBound(c);
swap(pi[$-d-1], e.front);
l += dist(pi[$-d-1..$], bi[$-d-1..$]);
}
r += l;
}
writeln(r);
}
auto dist(long[] pi, long[] bi)
{
return zip(pi, bi).map!(a => abs(a[0] - a[1])).sum;
}