Cod sursa(job #1157130)

Utilizator darrenRares Buhai darren Data 28 martie 2014 11:44:47
Problema Rsir Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <fstream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int T0, T1, a, b, x, y, z, M;
int A[7002], B[7002], C[7002], D[7002];
long long N;

int main()
{
    ifstream fin("rsir.in");
    ofstream fout("rsir.out");

    fin >> T0 >> T1 >> a >> b >> x >> y >> z >> M >> N;
    a %= M;
    b %= M;
    x %= M;
    y %= M;
    z %= M;

    for (int i = 0; i < M; ++i)
    {
        A[i] = 1LL * a * i * i % M;
        B[i] = 1LL * b * i * i % M;
        C[i] = 1LL * x * i % M;
        D[i] = 1LL * y * i % M;
    }


    if (N == 0)
    {
        fout << T0 << '\n';
        fin.close();
        fout.close();
        return 0;
    }
    if (N == 1)
    {
        fout << T1 << '\n';
        fin.close();
        fout.close();
        return 0;
    }

    T0 %= M;
    T1 %= M;

    int limit = min(N, 1LL * M * M + 2);
    for (int i = 2; i <= limit; ++i)
    {
        int aux = A[T0] + B[T1] + C[T0] + D[T1] + z;
        while (aux >= M) aux -= M;

        T0 = T1;
        T1 = aux;
    }

    if (N <= 1LL * M * M + 2)
    {
        fout << T1 << '\n';
        fin.close();
        fout.close();
        return 0;
    }

    int iT0 = T0, iT1 = T1, cycle = 0;
    while (true)
    {
        int aux = A[T0] + B[T1] + C[T0] + D[T1] + z;
        while (aux >= M) aux -= M;

        T0 = T1;
        T1 = aux;
        ++cycle;

        if (T0 == iT0 && T1 == iT1) break;
    }

    N -= M * M + 2;
    N = (N % cycle == 0 ? cycle : N % cycle);

    T0 = iT0;
    T1 = iT1;
    for (int i = 1; i <= N; ++i)
    {
        int aux = A[T0] + B[T1] + C[T0] + D[T1] + z;
        while (aux >= M) aux -= M;

        T0 = T1;
        T1 = aux;
    }

    fout << T1 << '\n';

    fin.close();
    fout.close();
}