181. X-Sequence
time limit per test: 0.5 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard
output: 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.
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
因为M比较小,且此递推关系是只和上一状态相关,所以我们可以知道此必定有周期,我们可以暴力找到周期和周期开始的点,然后就可以轻松解决,本题注意K=0的情况,具体的我在代码中打了注释。
贴上代码:
因为M比较小,且此递推关系是只和上一状态相关,所以我们可以知道此必定有周期,我们可以暴力找到周期和周期开始的点,然后就可以轻松解决,本题注意K=0的情况,具体的我在代码中打了注释。
贴上代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 1010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
int a,alpha,beta,gamma,k,M,b,A,T;
int at[2*nMax];
int ans[2*nMax];
int main(){
scanf("%d%d%d%d%d%d",&a,&alpha,&beta,&gamma,&M,&k);
if(k==0) { //注意K=0的情况,输出原值,不是%M的值
printf("%d\n",a);
return 0;
}
CLR(at,-1);
a%=M;
at[a]=0;
b=a;
ans[0]=a;
alpha%=M,beta%=M,gamma%=M;
for(int i=1;;i++){
a=ans[i-1];
b=a*a%M;b=b*alpha%M;
b=(b+a*beta)%M;
a=ans[i]=(b+gamma)%M;
if(k<=i) {
printf("%d\n",ans[k]);
return 0;
}
if(at[a]!=-1) {
T=i-at[a]; //周期
k=(k-at[a])%T; // at[i] 是周期开始的地方,前面at[i]个数是没有在周期里的
printf("%d\n",ans[at[a]+k]);
return 0;
} else {
at[a]=i;
}
}
return 0;
}