HDU 1005 Number Sequence 矩阵乘法 Fib数列

来源:互联网 发布:sql2005数据库无法访问 编辑:程序博客网 时间:2024/05/08 03:56

原题: 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): 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;}
0 0
原创粉丝点击