数学(矩阵乘法):HDU 4565 So Easy!
2016-08-11 14:43
381 查看
So Easy!
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3804 Accepted Submission(s): 1251
[align=left]Problem Description[/align]
A sequence Sn is defined as:
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate Sn.
You, a top coder, say: So easy!
[align=left]Input[/align]
There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.
[align=left]Output[/align]
For each the case, output an integer Sn.
[align=left]Sample Input[/align]
2 3 1 2013
2 3 2 2013
2 2 1 2013
[align=left]Sample Output[/align]
4
14
4
这道题还是有点门路的,需要一些巧法。
由于(a-1)2< b < a2,可以得出a-1<sqrt(b)<a,0<a-sqrt(b)<1。
这时构建E(n)=(a+sqrt(b))^n+(a-sqrt(b))^n,发现E(n)是整数,而且(a-sqrt(b))^n小于1,那么(a+sqrt(b))^n向上取整就是E(n)。
通过推导可以得出E(0)=2,E(1)=2*a,E(n)=2*a*E(n-1)-(a*a-b)*E(n-2),用矩阵乘法快速求出即可。
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> using namespace std; const int maxn=210; int a,b,n,m; struct Array{ int a[maxn],L; void Init(int x){L=x;memset(a,0,sizeof(a));} int *operator[](int x){return &a[(x-1)*L];} }; struct Matrix{ int R,C; Array mat; void Init(int r,int c){mat.Init(c);R=r;C=c;} int *operator[](int x){return mat[x];} friend Matrix operator*(Matrix a,Matrix b){ Matrix c;c.Init(a.R,b.C); for(int i=1;i<=a.R;i++) for(int j=1;j<=b.C;j++) for(int k=1;k<=a.C;k++) (c[i][j]+=1ll*a[i][k]*b[k][j]%m)%=m; return c; } friend Matrix operator^(Matrix a,int k){ Matrix c;c.Init(a.R,a.C); for(int i=1;i<=a.R;i++)c[i][i]=1; while(k){if(k&1)c=c*a;k>>=1;a=a*a;} return c; } }A,B; int main(){ while(scanf("%d%d%d%d",&a,&b,&n,&m)!=EOF){ A.Init(2,2); A[1][1]=2*a%m;A[1][2]=(b-1ll*a*a%m+m)%m; A[2][1]=1;A[2][2]=0; B.Init(2,1); B[1][1]=2*a%m; B[2][1]=2; A=A^(n-1);B=A*B; printf("%d\n",B[1][1]); } return 0; }
相关文章推荐
- postfix+sasl+dovecot
- 微信公众号里打开链接下载APP
- druid连接数据库加解密
- phpcms v9 下拉菜单 二级 三级子栏目调用方法
- jQueryUI datepicker 报错: TypeError: inst is undefined
- 一些命令行操作时候可以使用的快捷键
- bootstrap教程(二) —— 列表组listgroup
- 问题总结
- 【学习笔记】linux系统管理
- JavaScript closure的一个问题
- javascript同源策略和跨域实验及其跨域解决办法
- 数据分析常用数据源汇总
- 自定义吐司Toast
- 分享一个用OnGUI在手机上打印调试信息的工具类
- a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单
- 解决Android4.4及以上系统获取系统图片失败的问题,例如华为手机,调系统图库的时候就出现异常
- 浅谈tomcat
- Python网络数据采集10(译者:哈雷)
- ubuntu如何开启root,如何启用Ubuntu中root帐号
- win10系统下SQL2012下载及安装