分享

HDU 1005 Number Sequence 矩阵乘法 Fib数列

 长沙7喜 2018-10-11

原题: http://acm./showproblem.php?pid=1005

题目:

Number Sequence

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

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

思路:

按规律求出第n项。
由矩阵乘法我们可以知道:
这里写图片描述

所以对于fib数列我们可以用矩阵来求,由于矩阵可以左乘右乘,所以我们可以用快速幂来优化。

代码:

#include<iostream>
#include"string.h"
#include<stdio.h>
using namespace std;

const int bc=2;
const int mod = 7;
struct matrix
{
    int x[bc][bc];
};



matrix mutimatrix(matrix a,matrix b)
{
    matrix temp;
    memset(temp.x,0,sizeof(temp.x));
    for(int i=0;i<bc;i++)    //答案的行
    {
        for(int j=0;j<bc;j++)   //答案的列
        {
            for(int k=0;k<bc;k++)
            {
                temp.x[i][j]+=a.x[i][k]*b.x[k][j];
                temp.x[i][j]%=mod;
            }
        }
    }
    return temp;
}

matrix powmatrix(matrix a,int b)
{
    matrix temp;
    memset(temp.x,0,sizeof(temp.x));
    //初始化矩阵为单位阵
    for(int i=0;i<bc;i++)
        temp.x[i][i]=1;
    while(b)
    {
        if(b%2==1)
            temp=mutimatrix(temp,a);
        a=mutimatrix(a,a);
        b=b/2;
    }
    return temp;
}

int main()
{
    int a,b,n;
    //freopen("in.txt","r",stdin);
    while(scanf("%d %d %d",&a,&b,&n)!=EOF)
    {
        if(a==0&&b==0&&n==0) break;
        matrix st;
        //因为每次都是a个F(n-1)和b个F(n-2)相加,所以这里如此初始化
        //Fib数列这里就直接单位阵
        st.x[0][0]=a;
        st.x[0][1]=1;
        st.x[1][0]=b;
        st.x[1][1]=0;
        st=powmatrix(st,n-1);
        printf("%d\n",(st.x[0][1]+st.x[1][1])%mod);
    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多