Number Sequence(快速幂矩阵)

时间:2023-12-16 18:23:26

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1005

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 131753    Accepted Submission(s): 31988

Problem Description
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
Author
CHEN, Shunbao
Source
题意:简单的快速幂矩阵,加一个f(n-1) = f(n-1)即可
代码:
 #include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct Mtr{
int a , b , c , d ;
Mtr operator * (const Mtr m) const
{
Mtr res ;
res.a = (a*m.a% + b*m.c%)%;
res.b = (a*m.b%+b*m.d%)%;
res.c = (c*m.a%+d*m.c%)%;
res.d = (c*m.b%+d*m.d%)%;
return res;
}
};
int cal(Mtr a , int n)
{
Mtr c;
c.a = c.d = ;
c.b = c.c = ;
while(n>)
{
if(n&)
c = c*a;
a = (a*a);
n/=;
}
return (c.a+c.b)%;
}
int main()
{
int a , b , n;
while(~scanf("%d%d%d",&a,&b,&n)&&(a!=||b!=||n!=))
{
Mtr tm;
tm.a = a;
tm.b = b;
tm.c = ;
tm.d = ;
int tt = cal(tm,n-);
printf("%d\n",tt);
}
return ;
}