結果

問題 No.270 next_permutation (1)
ユーザー te-shte-sh
提出日時 2017-06-05 16:13:13
言語 D
(dmd 2.106.1)
結果
TLE  
実行時間 -
コード長 930 bytes
コンパイル時間 1,375 ms
コンパイル使用メモリ 150,772 KB
実行使用メモリ 8,756 KB
最終ジャッジ日時 2023-09-03 13:56:50
合計ジャッジ時間 5,717 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
8,756 KB
testcase_01 AC 12 ms
4,376 KB
testcase_02 AC 16 ms
4,376 KB
testcase_03 TLE -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
権限があれば一括ダウンロードができます

ソースコード

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[]);

  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