結果

問題 No.270 next_permutation (1)
ユーザー izuru_matsuuraizuru_matsuura
提出日時 2016-11-15 18:34:40
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 28 ms / 2,000 ms
コード長 1,492 bytes
コンパイル時間 1,326 ms
コンパイル使用メモリ 151,836 KB
実行使用メモリ 11,044 KB
最終ジャッジ日時 2023-09-02 22:54:38
合計ジャッジ時間 2,900 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,372 KB
testcase_01 AC 2 ms
4,372 KB
testcase_02 AC 3 ms
4,368 KB
testcase_03 AC 2 ms
4,368 KB
testcase_04 AC 3 ms
4,372 KB
testcase_05 AC 3 ms
4,368 KB
testcase_06 AC 3 ms
4,372 KB
testcase_07 AC 2 ms
4,368 KB
testcase_08 AC 3 ms
4,372 KB
testcase_09 AC 6 ms
4,368 KB
testcase_10 AC 26 ms
10,508 KB
testcase_11 AC 28 ms
11,044 KB
testcase_12 AC 28 ms
10,380 KB
testcase_13 AC 24 ms
10,092 KB
testcase_14 AC 25 ms
10,368 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.algorithm;
import std.array;
import std.ascii;
import std.container;
import std.conv;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void log(A...)(A arg) {
    stderr.writeln(arg);
}
int size(T)(in T s) {
    return cast(int)s.length;
}

long calc(in long[] a, in long[] b) {
    assert(a.size == b.size);
    long ans = 0;
    foreach (i; 0 .. a.size) {
        ans += abs(a[i] - b[i]);
    }
    return ans;
}

void main() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readln.chomp.split(" ").map!(to!long).array;
    auto B = readln.chomp.split(" ").map!(to!long).array;
    if (K == 0) {
        writeln(0);
        return;
    }
    if (N <= 10) {
        long ans = 0;
        do {
            ans += calc(P, B);
            K--;
            nextPermutation(P);
        } while (K > 0);
        writeln(ans);
        return;
    }

    long[] yabaikeesu;
    for (long i = N - 9; i <= N; i++) {
        yabaikeesu ~= i;
    }

    long ans = 0;
    long base = calc(P[0 .. $ - 10], B[0 .. $ - 10]);
    auto p = P[$ - 10 .. $];
    auto b = B[$ - 10 .. $];
    do {
        ans += base + calc(p, b);
        nextPermutation(p);
        if (p == yabaikeesu) {
            auto wp = P[0 .. $ - 10] ~ p;
            nextPermutation(wp);
            base = calc(wp[0 .. $ - 10], B[0 .. $ - 10]);
            p = wp;
        } else {
            K--;
        }
    } while (K > 0);
    writeln(ans);

}
0