結果

問題 No.658 テトラナッチ数列 Hard
ユーザー nanaenanae
提出日時 2018-03-03 16:53:33
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 777 ms / 2,000 ms
コード長 1,942 bytes
コンパイル時間 591 ms
コンパイル使用メモリ 84,280 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-03 18:58:29
合計ジャッジ時間 4,821 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 5 ms
4,376 KB
testcase_04 AC 274 ms
4,380 KB
testcase_05 AC 315 ms
4,380 KB
testcase_06 AC 403 ms
4,380 KB
testcase_07 AC 431 ms
4,380 KB
testcase_08 AC 518 ms
4,376 KB
testcase_09 AC 777 ms
4,380 KB
testcase_10 AC 776 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array;


void main() {
    int[][] A = [[1,1,1,1], [1,0,0,0], [0,1,0,0], [0,0,1,0]];

    int q;
    scan(q);

    while (q--) {
        long n;
        scan(n);
        n--;

        auto res = mul(powMat(A, n), [[1],[0],[0],[0]]);
        writeln(res[3][0]);
    }
}

int[][] powMat(int[][] A, long x) {
    if (x > 0) {
        auto res = square(powMat(A, x>>1));
        if (x & 1) {
            res = mul(res, A);
        }
        return res;
    }
    else {
        auto res = new int[][](A.length, A.length);
        foreach (i ; 0 .. A.length) res[i][i] = 1;
        return res;
    }
}

int[][] square(int[][] A) {
    assert(A[0].length == A.length);
    auto B = new int[][](A.length, A.length);

    foreach (i ; 0 .. A.length) {
        foreach (j ; 0 .. A.length) {
            foreach (k ; 0 .. A.length) {
                B[i][j] += A[i][k] * A[k][j];
                B[i][j] %= 17;
            }
        }
    }

    return B;
}


auto mul(int[][] A, int[][] B) {
    assert(A[0].length == B.length);
    auto N = A.length;
    auto M = B[0].length;

    auto C = new int[][](N, M);

    foreach (i ; 0 .. N) {
        foreach (j ; 0 .. M) {
            foreach (k ; 0 .. A[i].length) {
                C[i][j] += A[i][k] * B[k][j];
                C[i][j] %= 17;
            }
        }
    }

    return C;
}


void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}



void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}
0