sgu 181 X-Sequence

18 篇文章 0 订阅
181. X-Sequence
time limit per test: 0.5 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

因为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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值