sgu 181. X-Sequence 答案出現循環

181. X-Sequence

time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard



Let {xi} be the infinite sequence of integers: 
1) x0 = A; 
2) xi = (alpha * xi-1^2 + beta * xi-1 + gamma) mod M, for i >= 1. 
Your task is to find xk if you know A, alpha, beta, gamma, M and k.

Input
Given A (1 <= A <= 10000), alpha (0 <= alpha <= 100), beta (0 <= beta <= 100), gamma (0 <= gamma <= 100), M (1 <= M <= 1000), k (0 <= k <= 10^9). All numbers are integer.

Output
Write xk.

Sample test(s)

Input
1 1 1 1 10 1
Output
3


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll n[10000];

int check(int x){
    for(int i=x-1;i>=1;i--){
        if(n[x]==n[i])return i;
    }
    return -1;
}

int main(){
    ll A,a,b,c,M,k;
    scanf("%I64d%I64d%I64d%I64d%I64d%I64d",&A,&a,&b,&c,&M,&k);
    if(k==0){
        printf("%I64d",A);
        return 0;
    }
    n[0]=A;
    for(int i=1;;i++){
        n[i]=(a*n[i-1]*n[i-1]%M+b*n[i-1]%M+c)%M;
        if(k==i){
            printf("%I64d",n[k]);
            return 0;
        }
        int ans=check(i);
        if(ans==-1)continue;
        printf("%I64d",n[ans+(k-ans)%(i-ans)]);
        return 0;
    }
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章