Cod sursa(job #3377146)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 21 noiembrie 2026 20:49:46
Problema Rsir Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.52 kb
#include <fstream>
#include <utility>

using namespace std;

#pragma GCC optimize("O3,unroll-loops")

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

typedef long long int ll;
ll T0, T1, a, b, x, y, z, n, MOD;

typedef pair<ll, ll> State;

inline State f(const State& s) {
    ll t_prev2 = s.first;
    ll t_prev1 = s.second;

    ll t_next = (a * t_prev2 * t_prev2 +
                 b * t_prev1 * t_prev1 +
                 x * t_prev2 +
                 y * t_prev1 +
                 z) % MOD;

    return {t_prev1, t_next};
}

int main() {
    ios::sync_with_stdio(false);
    fin.tie(nullptr);
    fin >> T0 >> T1 >> a >> b >> x >> y >> z >> MOD >> n;


    State start = {T0 % MOD, T1 % MOD};

    State tortoise = f(start);
    State rabbit = f(f(start));

    while (tortoise != rabbit) {
        tortoise = f(tortoise);
        rabbit = f(f(rabbit));
    }

    ll period_start = 0;
    tortoise = start;
    while (tortoise != rabbit) {
        tortoise = f(tortoise);
        rabbit = f(rabbit);
        period_start++;
    }

    if (n <= period_start) {
        State ans = start;
        for (ll i = 0; i < n; i++) {
            ans = f(ans);
        }
        fout << ans.first << '\n';
        return 0;
    }

    rabbit = f(tortoise);
    ll period_length = 1;
    while (tortoise != rabbit) {
        rabbit = f(rabbit);
        period_length++;
    }

    ll rem_steps = (n - period_start) % period_length;
    State ans = tortoise;
    while (rem_steps--)
        ans = f(ans);


    fout << ans.first << '\n';
    return 0;
}