Cod sursa(job #2147747)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 28 februarie 2018 22:54:21
Problema Iepuri Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 kb
#include <fstream>
#define MOD 666013

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

struct Matrix {
    long long int mat[3][3];
};

const Matrix nullMat = {
    {{1, 0, 0},
     {0, 1, 0},
     {0, 0, 1}}
};

Matrix prod(Matrix a, Matrix b) {
    Matrix ret = {};
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
                ret.mat[i][j] = (ret.mat[i][j] + a.mat[i][k] * b.mat[k][j] % MOD) % MOD;
    return ret;
}

Matrix pow(Matrix mat, int exp) {
    if (!exp)
        return nullMat;

    if (exp & 1)
        return prod(mat, pow(prod(mat, mat), exp >> 1));
    return pow(prod(mat, mat), exp >> 1);
}

int main() {
    int t, n;
    int x, y, z;
    int a, b, c;

    fin >> t;
    for (int it = 0; it < t; it++) {
        fin >> x >> y >> z;
        fin >> a >> b >> c;

        fin >> n;
        if (!n) {
            fout << x << '\n';
            continue;
        }
        else if (n == 1) {
            fout << y << '\n';
            continue;
        }
        else if (n == 2) {
            fout << z << '\n';
            continue;
        }

        int day3 = a * z + b * y + c * x;
        int day4 = a * day3 + b * z + c * y;

        Matrix initMat = {
            {{day4, day3, z},
             {day3,    z, y},
             {   z,    y, x}}
        };

        Matrix expoMat = {
            {{a, 1, 0},
             {b, 0, 1},
             {c, 0, 0}}
        };

        fout << prod(initMat, pow(expoMat, n - 2)).mat[1][1] << '\n';
    }

    fout.close();
    return 0;
}