Cod sursa(job #1661848)

Utilizator hrazvanHarsan Razvan hrazvan Data 24 martie 2016 11:15:46
Problema Rsir Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 1.87 kb
#include <stdio.h>
#define MAXM 7000
int p1[MAXM], p2[MAXM];

void precalc(int a, int b, int x, int y, int z, int m){
  int i;
  for(i = 0; i < m; i++){
    p1[i] = (1LL * a * i * i + x * i + z) % m;
    p2[i] = ((1LL * b * i * i) + y * i) % m;
  }
}

inline void next(int *x, int *y, int m){
  int z;
  z = p1[*x] + p2[*y];
  if(z >= m)
    z -= m;
  *x = *y;
  *y = z;
}

inline int val(int x, int y, int m){
  int z;
  z = p1[x] + p2[y];
  if(z >= m)
    z -= m;
  return z;
}

int main(){
  FILE *in = fopen("rsir.in", "r");
  FILE *out = fopen("rsir.out", "w");
  int f0, f1, a, b, x, y, z, m, i, t1, t2, h1, h2, pw, mu, lam;
  long long n;
  fscanf(in, "%d%d%d%d%d%d%d%d%lld", &f0, &f1, &a, &b, &x, &y, &z, &m, &n);
  fclose(in);
  f0 %= m;  f1 %= m;  a %= m;  b %= m;  x %= m;  y %= m;  z %= m;
  precalc(a, b, x, y, z, m);
  if(n == 0)
    fprintf(out, "%d", f0);
  else  if(n == 1)
    fprintf(out, "%d", f1);
  else{
    n--;
    t1 = f0;  t2 = f1;
    h1 = f0;  h2 = f1;
    next(&t1, &t2, m);
    next(&h1, &h2, m);
    next(&h1, &h2, m);
    while(t1 != h1 || t2 != h2){
      next(&t1, &t2, m);
      next(&h1, &h2, m);
      next(&h1, &h2, m);
    }
    mu = 0;
    t1 = f0;  t2 = f1;
    while(t1 != h1 || t2 != h2){
      next(&t1, &t2, m);
      mu++;
    }
    h1 = t1;  h2 = t2;
    next(&h1, &h2, m);
    lam = 1;
    while(t1 != h1 || t2 != h2){
      next(&h1, &h2, m);
      lam++;
    }
    if(n <= mu){
      h1 = f0;  h2 = f1;
      for(i = 1; i < n; i++)
        next(&h1, &h2, m);
      fprintf(out, "%d", val(h1, h2, m));
    }
    else{
      h1 = f0;  h2 = f1;
      for(i = 0; i < mu; i++){
        next(&h1, &h2, m);
      }
      n -= mu;
      n %= lam;
      for(i = 1; i < n; i++)
        next(&h1, &h2, m);
      fprintf(out, "%d", val(h1, h2, m));
    }
  }
  fclose(out);
  return 0;
}