码迷,mamicode.com
首页 > 其他好文 > 详细

codevs 1281 Xn数列

时间:2016-09-03 20:59:47      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目描述 Description

给你6个数,m, a, c, x0, n, g

Xn+1 = ( aXn + c ) mod m,求Xn

m, a, c, x0, n, g<=10^18

输入描述 Input Description

一行六个数 m, a, c, x0, n, g

输出描述 Output Description

输出一个数 Xn mod g

样例输入 Sample Input

11 8 7 1 5 3

样例输出 Sample Output

2

  很久没有写博客了……先写道水题压压惊

  首先,由于Xi=Xi-1+a+c,那么Xn=a^n*X0+(a^(n-1)+a^(n-2)+a^(n-3)+……+a^1+a^0)*c。

  那么,写个快速幂,前面一部分就出来了。再假设solve(x)可以求出 a^(x-1)+a^(x-2)+a^(x-3)+……+a^1+a^0,那么 solve(x)=solve(x/2)*(a^(x/2)+1) (x%2==1),否则还要加上a^x

  最后,由于模数是10^18级别的。还要写个快速乘法。

  下面贴代码:

  

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
 7 
 8 using namespace std;
 9 typedef long long llg;
10 
11 llg m,a,c,x0,g,n,ans;
12 
13 void gi(llg &h){if(h>=m) h%=m;}
14 llg ch(llg a,llg b){
15     llg s=0;
16     if(a<b) swap(a,b);
17     while(b){
18         if(b&1) s+=a,gi(s);
19         a<<=1,gi(a); b>>=1;
20     }
21     return s;
22 }
23 
24 llg mi(llg a,llg b){
25     llg s=1;
26     while(b){
27         if(b&1) s=ch(s,a);
28         a=ch(a,a); b>>=1;
29     }
30     return s;
31 }
32 
33 llg solve(llg x){
34     if(!x) return 1;
35     llg s,u=(x-1)>>1;
36     s=ch(solve(u),mi(a,u+1)+1);
37     if(!(x&1)) s+=mi(a,x),gi(s);
38     return s;
39 }
40 
41 int main(){
42     scanf("%lld %lld %lld %lld %lld %lld",&m,&a,&c,&x0,&n,&g);
43     ans=ch(mi(a,n),x0);
44     ans+=ch(solve(n-1),c); gi(ans);
45     printf("%lld",ans%g);
46     return 0;
47 }

codevs 1281 Xn数列

标签:

原文地址:http://www.cnblogs.com/lcf-2000/p/5837820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!