HDU - 1005 Number Sequence(矩阵快速幂)
Number Sequence
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
题意:给了一个递推式f(n) = A * f(n - 1) + B * f(n - 2) ,已知这个递推式的第一项和第二项都为1,给出A,B的值,需要求这个递推式的第n项取余7。
思路:看到递推式就可以想到能用矩阵快速幂解决,利用递推式找出满足的关系矩阵:
最后记得取余一下7!
代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define lowbit(a) (a & (-a))
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
const int minn = 1e3 + 10;
const double PI = acos(-1.0);
#define mod 1000000007
#define eps 1e-10
/*------------------------------------------------------*/
int N = 2;
struct Matrix
{
int mp[2][2];
Matrix()
{
memset(mp, 0, sizeof(mp));
}
void init()
{
memset(mp, 0, sizeof(mp));
for (int i = 0; i < N; i++)
mp[i][i] = 1;
}
};
Matrix mul(Matrix a, Matrix b)
{
Matrix ans;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
ans.mp[i][j] = ((ans.mp[i][j] % 7) + ((a.mp[i][k] % 7) * (b.mp[k][j] % 7)) % 7) % 7;
return ans;
}
Matrix mat_pow(Matrix a, int b)
{
Matrix ans;
ans.init();
while (b)
{
if (b & 1)
ans = mul(ans, a);
a = mul(a, a);
b >>= 1;
}
return ans;
}
int main()
{
int a, b, n;
while (~scanf("%d %d %d", &a, &b, &n))
{
if (a == 0 && b == 0 && n == 0)
break;
if (n == 1 || n == 2)
printf("1\n");
else
{
Matrix cnt;
cnt.init();
cnt.mp[0][0] = a;
cnt.mp[0][1] = b;
cnt.mp[1][0] = 1;
cnt.mp[1][1] = 0;
cnt = mat_pow(cnt, n - 2);
printf("%d\n", (cnt.mp[0][0] + cnt.mp[0][1]) % 7);
}
}
return 0;
}
本文地址:https://blog.csdn.net/weixin_44137005/article/details/110629846
上一篇: 妹子你真钞掉了一地
下一篇: 咱先不喝酒,咱先赏菊
推荐阅读