Reading comprehension HDU - 4990(矩阵快速幂 递推)
2018-02-13 11:14
435 查看
Read the program below carefully then answer the question. #pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include<iostream> #include <cstring> #include <cmath> #include <algorithm> #include<vector> const int MAX=100000*2; const int INF=1e9; int main() { int n,m,ans,i; while(scanf("%d%d",&n,&m)!=EOF) { ans=0; for(i=1;i<=n;i++) { if(i&1)ans=(ans*2+1)%m; else ans=ans*2%m; } printf("%d 4000 \n",ans); } return 0; }
Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
Output
For each case,output an integer,represents the output of above program.
Sample Input
1 10 3 100
Sample Output
1 5
题意:当n为奇数时,f
= 2*f[n-1]+1,f[n-1] = 2*f[n-2],所以:f
= f[n-1] + 2*f[n-2] + 1;
当n为偶数时,f
= 2*f[n-1],f[n-1] = 2*f[n-2] + 1,所以:f
= f[n-1] + 2*f[n-2] + 1;
综上:f
= f[n-1] + 2*f[n-2] + 1,构造矩阵:
利用矩阵快速幂求f(n)
#include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; typedef long long LL; LL MOD; const int Size = 3; struct MA { LL mat[Size][Size]; }; MA mul(MA x, MA y) { MA ret; memset(ret.mat, 0, sizeof(ret.mat)); for(int i = 0; i<Size; i++) for(int j = 0; j<Size; j++) for(int k = 0; k<Size; k++) { ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD; ret.mat[i][j] %= MOD; } return ret; } MA qpow(MA x, LL y) { MA s; memset(s.mat,0,sizeof(s.mat)); for(int i=0;i<Size;i++) s.mat[i][i] = 1; while(y) { if(y&1) s = mul(s, x); x = mul(x, x); y >>= 1; } return s; } MA tmp = { 1, 2, 1, 1, 0, 0, 0, 0, 1 }; int main() { LL n, m; while(~scanf("%lld%lld",&n,&m)) { MOD = m; if(n<=2) { printf("%lld\n", n%MOD); continue; } MA s = tmp; s = qpow(s, n-2); LL ans = ((2LL*s.mat[0][0]%MOD + s.mat[0][1])%MOD+s.mat[0][2])%MOD; printf("%lld\n", ans); } }
相关文章推荐
- Reading comprehension HDU - 4990(矩阵快速幂)
- HDU 4990 (找规律 矩阵快速幂)
- HDU 4990 Reading comprehension(找规律+矩阵快速幂)
- Reading comprehension HDU - 4990
- HDU 5015 233Matrix(矩阵快速幂+递推)
- HDU 4990 Reading comprehension(找规律+矩阵快速幂)
- hdu4990——Reading comprehension(矩阵快速幂)
- ICPC 沈阳站C题 HDU 5950 Recursive sequence 矩阵快速幂 线性递推
- hdu 4990 矩阵快速幂
- HDU 4990 Reading comprehension(找规律+矩阵快速幂)
- hdu 4602 递推关系矩阵快速幂模
- HDU 2842 Chinese Rings(矩阵快速幂+递推)
- HDU 4990 Reading comprehension(找规律+矩阵快速幂)
- HDU 4990 Reading comprehension 矩阵快速幂
- hdu 4990 Reading comprehension 矩阵快速幂
- hdu 2842(矩阵快速幂+递推)
- HDU 4990 Reading comprehension(找规律+矩阵快速幂)
- HDU 5667 矩阵快速幂关于指数的递推
- hdu 4990 Reading comprehension(矩阵快速幂)
- HDU 2604 Queuing [递推]【矩阵快速幂】