本文主要是介绍HDU - 4990 - Reading comprehension(找规律 + 矩阵快速幂),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4990
题意:给n和m,问如果按给的程序执行,最后得结果是多少。
思路:打表找规律,显然可以得到递推式:,然后构造矩阵即可。
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 3;
ll n, k, MOD, ans;
struct Matrix
{ll m[MAXN][MAXN];void init(int x){memset(m, 0, sizeof(m));for(int i = 0; i < MAXN; i++){m[i][i] = x;}}Matrix operator * (const Matrix &a) const{Matrix res;res.init(0);for(int i = 0; i < MAXN; i++)for(int j = 0; j < MAXN; j++)for(int k = 0; k < MAXN; k++)res.m[i][j] = (res.m[i][j] + (m[i][k] * a.m[k][j]) % MOD) % MOD;return res;}Matrix operator + (const Matrix &a) const{Matrix ans;ans.init(0);for(int i = 0; i < MAXN; i++)for(int j = 0; j < MAXN; j++)ans.m[i][j] = (ans.m[i][j] + (m[i][j] + a.m[i][j]) % MOD) % MOD;return ans;}
};Matrix quickPow(Matrix x, ll p)
{Matrix res;res.init(1);x = x * res;while(p){if(p & 1) res = res * x;p >>= 1;x = x * x;}return res;
}
void output(Matrix a)
{for(int i = 0; i < n; i++)for(int j = 0; j < n; j++)printf("%lld%c",a.m[i][j], j == n - 1 ? '\n' : ' ');
}Matrix a, x;void init()
{a.m[0][0] = 1; a.m[0][1] = 2; a.m[0][2] = 1;a.m[1][0] = 1; a.m[1][1] = 0; a.m[1][2] = 0;a.m[2][0] = 0; a.m[2][1] = 0; a.m[2][2] = 1;x.m[0][0] = 1;x.m[1][0] = 0;x.m[2][0] = 1;
}
int main()
{while(~scanf("%lld%lld", &n, &MOD)){init();a = quickPow(a, n) * x;printf("%lld\n", a.m[1][0]);}return 0;
}
/*
1 10
3 100
---------
1
5
*/
这篇关于HDU - 4990 - Reading comprehension(找规律 + 矩阵快速幂)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!