Cod sursa(job #2122795)

Utilizator LucianTLucian Trepteanu LucianT Data 5 februarie 2018 15:06:54
Problema Rsir Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.28 kb
#include <bits/stdc++.h>
using namespace std;
const int maxM=7000;

struct nod{
    int val;
    int prev1;
    int prev2;

    bool operator == (const nod &alt)const{
        return val==alt.val && prev1==alt.prev1;
    }

    bool operator != (const nod &alt)const{
        return val!=alt.val || prev1!=alt.prev1;
    }
}T2;

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

int prec1[maxM];
int prec2[maxM];

nod nxt(nod A)
{
    nod res;
    res.prev2=A.prev1;
    res.prev1=A.val;

    res.val=prec1[res.prev1]+prec2[res.prev2];

    //res.val=1LL*(1LL*b*res.prev1*res.prev1+1LL*y*res.prev1+1LL*z)%MOD;
    //res.val+=1LL*(1LL*a*(res.prev2)*(res.prev2)+1LL*x*(res.prev2))%MOD;

    while(res.val>=MOD)
        res.val-=MOD;

    return res;
}

int main()
{
    freopen("rsir.in","r",stdin);
    freopen("rsir.out","w",stdout);

    scanf("%d%d%d%d%d%d%d%d%lld",&T0,&T1,&a,&b,&x,&y,&z,&MOD,&n);
    T0%=MOD; T1%=MOD;
    a%=MOD; b%=MOD;
    x%=MOD; y%=MOD; z%=MOD;

    T2.prev1=T1;
    T2.prev2=T0;

    T2.val=(1LL*b*(T1)*(T1)+1LL*y*(T1)+1LL*z)%MOD;
    T2.val+=1LL*(1LL*a*T0*T0+1LL*x*T0)%MOD;

    for(int i=0;i<maxM;i++){
        prec1[i]=(1LL*b*i*i+1LL*y*i+1LL*z)%MOD;
        prec2[i]=(1LL*a*i*i+1LL*x*i)%MOD;
    }

    if(T2.val>=MOD)
        T2.val-=MOD;

    int cycSize=1;
    int queSize=0;

    nod lento=nxt(T2);
    nod fasto=nxt(nxt(T2));

    while(lento!=fasto){
        lento=nxt(lento);
        fasto=nxt(nxt(fasto));
    }

    lento=T2;
    while(lento!=fasto){
        queSize++;
        lento=nxt(lento);
        fasto=nxt(fasto);
    }

    fasto=nxt(lento);
    while(lento!=fasto){
        fasto=nxt(fasto);
        cycSize++;
    }

    cerr<<queSize<<" "<<cycSize;

    if(n==0){
        printf("%d",T0);
        return 0;
    }
    if(n==1){
        printf("%d",T1);
        return 0;
    }

    n-=2;
    if(n<queSize){
        nod sol=T2;
        for(int i=1;i<=n;i++)
            sol=nxt(sol);
        printf("%d",sol.val);
    }
    else{
        nod sol=T2;
        for(int i=1;i<=queSize;i++)
            sol=nxt(sol);

        n-=queSize;
        n%=cycSize;

        for(int i=1;i<=n;i++)
            sol=nxt(sol);
        printf("%d",sol.val);
    }

    return 0;
}