HDU 5667 Sequence(数论+矩阵快速幂)
2016-05-03 10:30
417 查看
Description
已知数列f(n)的递推公式如下:
现给出n,a,b,c,p,求f(n)%p
Input
第一行为一整数T表示用例组数,每组用例占一行包括五个整数n,a,b,c,p
(1≤T≤10,1≤n≤10^18,1≤a,b,c≤10^9,p是素数且p≤10^9+7)
Output
对于每组用例,输出f(n)%p
Sample Input
1
5 3 3 3 233
Sample Output
190
Solution
费马小定理+矩阵快速幂
Code
已知数列f(n)的递推公式如下:
现给出n,a,b,c,p,求f(n)%p
Input
第一行为一整数T表示用例组数,每组用例占一行包括五个整数n,a,b,c,p
(1≤T≤10,1≤n≤10^18,1≤a,b,c≤10^9,p是素数且p≤10^9+7)
Output
对于每组用例,输出f(n)%p
Sample Input
1
5 3 3 3 233
Sample Output
190
Solution
费马小定理+矩阵快速幂
Code
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> #include<ctime> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define maxn 11 typedef long long ll; struct Mat { ll mat[maxn][maxn];//矩阵 int row,col;//矩阵行列数 }; Mat mod_mul(Mat a,Mat b,int p)//矩阵乘法 { Mat ans; ans.row=a.row; ans.col=b.col; memset(ans.mat,0,sizeof(ans.mat)); for(int i=0;i<ans.row;i++) for(int k=0;k<a.col;k++) if(a.mat[i][k]) for(int j=0;j<ans.col;j++) { ans.mat[i][j]+=a.mat[i][k]*b.mat[k][j]; ans.mat[i][j]%=p; } return ans; } Mat mod_pow(Mat a,ll k,ll p)//矩阵快速幂 { //printf("k=%I64d p=%I64d\n",k,p); Mat ans; ans.row=a.row; ans.col=a.col; for(int i=0;i<a.row;i++) for(int j=0;j<a.col;j++) ans.mat[i][j]=(i==j); while(k) { if(k&1)ans=mod_mul(ans,a,p); a=mod_mul(a,a,p); k>>=1; } return ans; } ll Mod_pow(ll a,ll b,ll p) { a%=p; ll ans=1ll; while(b) { if(b&1)ans=ans*a%p; a=a*a%p; b>>=1; } return ans; } int main() { int T; ll n,a,b,c,p; scanf("%d",&T); while(T--) { scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p); Mat A,B; A.row=A.col=3; A.mat[0][0]=c,A.mat[0][1]=1,A.mat[0][2]=b; A.mat[1][0]=1,A.mat[1][1]=0,A.mat[1][2]=0; A.mat[2][0]=0,A.mat[2][1]=0,A.mat[2][2]=1; if(n==1)printf("1\n"); else if(n==2)printf("%I64d\n",Mod_pow(a,b,p)); else { B=mod_pow(A,(n-2),(p-1)); ll temp=B.mat[0][0]*b+B.mat[0][2]; ll ans=Mod_pow(a,temp,p); printf("%I64d\n",ans); } } return 0; }
相关文章推荐
- LeetCode OJ 96. Unique Binary Search Trees
- String,StringBuffer与StringBuilder的区别??
- 使用hibernate出现的一个异常org.hibernate.PropertyAccessException: Null value was assigned to a property of pr
- iOS性能调优(全)---内存优化和UI优化
- iOS之蓝牙开发—CoreBluetooth详解二
- 【Android UI】ListView使用ViewHolder模式提高效率
- UIImageView常用属性和方法
- Dataquest用户数据分析
- PHP包含文件函数include、include_once、require、require_once区别总结
- 最长上升子序列 (Longest Increasing Subsequence, 常简称为 LIS)
- 有限状态机在单片机和 Arduino 编程中的应用
- UIAlertController设置
- Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
- iOS开发—— UIMenuController的使用
- LeetCode "Top K Frequent Elements"
- 【Arduino官方教程第一辑】示例程序 2-8 曲调2
- 【Arduino官方教程第一辑】示例程序 2-7 使用tone()函数弹奏一段小曲
- google base 之MessagePumpForUI
- bzoj 1345: [Baltic2007]序列问题Sequence(单调栈)
- Elasticsearch源码分析之一——使用Guice进行依赖注入与模块化系统