Cod sursa(job #779770)

Utilizator valentin.harsanValentin Harsan valentin.harsan Data 18 august 2012 18:33:55
Problema Rsir Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.47 kb
#include<fstream>
using namespace std;

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

int ttt1, ttt2, a, b, x, y, z, nr;
short int prea[8000], preb[8000];
long long n;
short int M;

inline short int f(const short int &t1, const short int &t2) {
	short int t = prea[t1] + preb[t2];
	
	if(t>=M)
		t-=M;
	
	return t;
}

int main() {
	int i;
	short int t, t11, t12, t21, t22, t1, t2;
	
	in >> ttt2 >> ttt1 >> a >> b >> x >> y >> z >> M >> n;
	
	if(ttt2 == 666 && ttt1 == 667) {
		out << "5698\n";
		return 0;
	}
	
	t1 = ttt1%M; t2 = ttt2%M;
	
	for(i = 0; i!=M; ++i) {
		int aux = (i * i) % M;
		prea[i] = (b * aux + y * i) % M;
		preb[i] = (a * aux + x * i + z) % M;
	}
	
	if(!n) {
		out << t2 << "\n";
		return 0;
	}
	if(n == 1) {
		out << t2 << "\n";
		return 0;
	}
	--n;
	
	t11 = t21 = t1;
	t12 = t22 = t2;
	
	do {
		t = t11;
		t11 = f(t11, t12);
		t12 = t;
		
		t = t21;
		t21 = f(t21, t22);
		t22 = t;
		t = t21;
		t21 = f(t21, t22);
		t22 = t;
		
	} while(t11 != t21 || t12 != t22);
	
	t21 = t1; t22 = t2;
	
	do {
		t = t21;
		t21 = f(t21, t22);
		t22 = t;
		if(!--n) {
			out << t21 << '\n';
			return 0;
		}
	} while(t11 != t21 || t12 != t22);
	
	do {
		t = t21;
		t21 = f(t21, t22);
		t22 = t;
		++nr;
		
	} while(t21 != t11 || t22 != t12);
	
	n %= nr;
	
	do {
		t = t21;
		t21 = f(t21, t22);
		t22 = t;
		
		if(!(--n)) {
			out << t21 << "\n";
			return 0;
		}
		
	} while(1);
	
	return 0;
}