Cod sursa(job #2182787)

Utilizator horiahoria1Horia Alexandru Dragomir horiahoria1 Data 22 martie 2018 17:14:51
Problema Iepuri Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <fstream>
#include <cstring>

#define MOD 666013
#define KMAX 3

void multiply_matrix(int A[KMAX][KMAX], int B[KMAX][KMAX], int C[KMAX][KMAX]) {

    int tmp[KMAX][KMAX];

    for (int i = 0; i < KMAX; ++i) {
        for (int j = 0; j < KMAX; ++j) {

            long long int sum = 0;

            for (int k = 0; k < KMAX; ++k) {
                sum += 1LL * A[i][k] * B[k][j];
            }

            tmp[i][j] = sum % MOD;
        }
    }

    memcpy(C, tmp, sizeof(tmp));

}

void power_matrix (int C[KMAX][KMAX], int power, int R[KMAX][KMAX]) {

    int tmp[KMAX][KMAX];

    for (int i = 0; i < KMAX; ++i) {
        for (int j = 0; j < KMAX; ++j) {
            tmp[i][j] = (i == j ? 1 : 0);
        }
    }

    while (power != 1) {
        if (power % 2 == 0) {
            multiply_matrix(C, C, C);
            power /= 2;
        } else {
            multiply_matrix(tmp, C, tmp);
            --power;
        }
    }

    multiply_matrix(C, tmp, R);

}

int solution (int x, int y, int z, int a, int b, int c, int n) {

    if (n == 1) {
        return x;
    }
    if (n == 2) {
        return y;
    }
    if (n == 3) {
        return z;
    }

    int dp[KMAX][KMAX] = {{0, 0, c},
                          {1, 0, b},
                          {0, 1, a}};

    power_matrix(dp, n - 2, dp);

    return (1LL * x * dp[0][2] + 1LL * y * dp[1][2] + 1LL * z * dp[2][2]) % MOD;

}

int main() {

    std::ifstream in("iepuri.in");
    std::ofstream out("iepuri.out");

    int t;
    in >> t;

    int x, y, z, a, b, c, n;

    for(int i = 0; i < t; ++i) {
        in >> x >> y >> z >> a >> b >> c >> n;
        out << solution (x, y, z, a, b, c, n) << '\n';
    }

    in.close();
    out.close();

    return 0;
}