Cod sursa(job #2177825)

Utilizator MihaelaCismaruMihaela Cismaru MihaelaCismaru Data 18 martie 2018 20:50:50
Problema Rsir Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.69 kb
#include<fstream>
#include<map>
using namespace std;
ifstream in ("rsir.in");
ofstream out ("rsir.out");
long long a,b,c,d,A,B,X,Y,Z,n,mod,aux,alfa,beta,ciclu,coada,s;
map<pair<int,int>,bool> hz;
int main (void) {
    in >> a >> b >> A >> B >> X >> Y >> Z >> mod >> n;
    a %= mod;
    b %= mod;
    // n e 0 sau 1
    if (n == 0) {
        out << a;
        return 0;
    }
    if (n == 1) {
        out << b;
        return 0;
    }

    // cautam unde incepe ciclul
    c = a; d = b;
    hz [{c,d}] = 1;
    while (true) {
        ciclu++;
        hz[{c,d}] = 1;
        aux = (A * c*c + B * d*d + X * c + Y * d + Z) % mod;
        if (hz[{d,aux}] == 1) {
            alfa = d;
            beta = aux;
            break;
        }
        c = d;
        d = aux;
    }

    // cautam cat de lunga e coada
    c = a;
    d = b;
    coada = 1;
    while (true) {
        coada++;
        aux = (A * c*c + B * d*d + X * c + Y * d + Z) % mod;
        if (n == coada) {
            out << aux;
            return 0;
        }
        if (alfa == d && beta == aux) {
            break;
        }
        c = d;
        d = aux;
    }
    coada -= 1;

    // daca elementul se afla in ciclu il cautam in ciclu
    ciclu -= coada;
    n -= coada;
    n %= ciclu;
    if (n == 0) {
        out << alfa;
        return 0;
    }
    if (n == 1) {
        out << beta;
        return 0;
    }

    c = alfa;
    d = beta;
    s = 1;
    while (true) {
        s++;
        aux = (A * c*c + B * d*d + X * c + Y * d + Z) % mod;
        if (s == n) {
            out << aux;
            return 0;
        }
        c = d;
        d = aux;
    }
    return 0;
}