結果

問題 No.270 next_permutation (1)
ユーザー te-shte-sh
提出日時 2017-06-05 16:16:05
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 56 ms / 2,000 ms
コード長 979 bytes
コンパイル時間 1,403 ms
コンパイル使用メモリ 153,056 KB
実行使用メモリ 8,476 KB
最終ジャッジ日時 2023-09-03 13:57:06
合計ジャッジ時間 2,638 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
4,380 KB
testcase_01 AC 12 ms
4,380 KB
testcase_02 AC 16 ms
4,384 KB
testcase_03 AC 1 ms
4,384 KB
testcase_04 AC 13 ms
4,380 KB
testcase_05 AC 13 ms
4,380 KB
testcase_06 AC 13 ms
4,388 KB
testcase_07 AC 5 ms
4,380 KB
testcase_08 AC 5 ms
4,380 KB
testcase_09 AC 16 ms
5,312 KB
testcase_10 AC 44 ms
8,408 KB
testcase_11 AC 56 ms
8,272 KB
testcase_12 AC 56 ms
8,456 KB
testcase_13 AC 39 ms
8,300 KB
testcase_14 AC 41 ms
8,476 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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;
}
0