hdu 1005 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).

思路:矩阵加速线性递推式。

这题第一次看是2012年11月2333,当时用pascal写的

/* ***********************************************
Author :111qqz
Created Time :Mon 31 Oct 2016 05:03:40 AM CST
File Name :code/hdu/1005.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6struct Mat
 7{
 8    LL mat[2][2];
 9    void clear()
10    {
11	ms(mat,0);
12    }
13}M,M1;
14Mat operator * ( Mat a,Mat b)
15{
16    Mat c;
17    c.clear();
18    for ( int i = 0 ;i  < 2 ; i ++)
19	for ( int j = 0 ; j < 2 ; j++)
20	    for ( int k = 0 ; k < 2 ; k++)
21		c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j] )%7;
22    return c;
23}
24Mat operator ^ ( Mat a,LL b)
25{
26    Mat res;
27    res.clear();
28    for ( int i = 0 ; i < 2 ; i++)
29	res.mat[i][i] = 1;
30    while (b>0)
31    {
32	if (b&1) res = res * a;
33	b = b >> 1LL;
34	a = a * a;
35    }
36    return res;
37}
38LL A,B,n;
39void init()
40{
41    M.clear();
42    M.mat[0][1] = 1;
43    M.mat[1][0] = B;
44    M.mat[1][1] = A;
45    M1.clear();
46    M1.mat[0][0] = 1;
47    M1.mat[1][0] = 1;
48}
49int main()
50{
51	#ifndef  ONLINE_JUDGE 
52	freopen("code/in.txt","r",stdin);
53  #endif
54	while (~scanf("%lld%lld%lld",&A,&B,&n))
55	{
56	    init();
57	    if (A==0&&B==0&&n==0) break;
58	    Mat res = (M^(n-2))*M1;
59	    printf("%lld\n",res.mat[1][0]);
	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}