hdu-1005

Number Sequence

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


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 31 2 100 0 0
 

Sample Output
 
  
2

5

解析:求斐波那契的一点改变。n=100000000,一看就知道常规的做法肯定要超时,所以就用到到了矩阵乘法。

代码:

 
   
#include<iostream>  
#include<memory.h>  
#include<cstdlib>  
#include<cstdio>  
#include<cmath>  
#include<cstring>  
#include<string>  
#include<cstdlib>  
#include<iomanip>  
#include<vector>  
#include<list>  
#include<map>  
#include<algorithm>  
typedef long long LL;  
const int maxn=1000+10;  
const int mod=7;  
const int N=2;  
using namespace std;  
struct Matrix  
{  
    int m[N][N];  
};
Matrix I=  
{  
    1,0,  
    0,1  
};  
Matrix multi(Matrix a,Matrix b)  
{  
    Matrix c;  
    for(int i=0;i<N;i++)  
    {  
        for(int j=0;j<N;j++)  
        {  
            c.m[i][j]=0;  
            for(int k=0;k<N;k++)  
                c.m[i][j]+=a.m[i][k]*b.m[k][j]%mod;  
  
            c.m[i][j]%=mod;  
        }  
    }  
    return c;  
}  
Matrix power(Matrix A,int k)  
{  
    Matrix ans=I,p=A;  
    while(k>0)  
    {  
        if(k&1)ans=multi(ans,p); 
            p=multi(p,p); 
        k>>=1;
         
    }  
    return ans;  
}
int main()  
{  
    int a,b,n;  
    while(~scanf("%d%d%d",&a,&b,&n))  
    {
        Matrix A;
        if(a==0&&b==0&&n==0)break;
        A.m[0][0]=a;
        A.m[0][1]=b;
        A.m[1][0]=1;
        A.m[1][1]=0;
        Matrix ans =power(A,n-2);
        printf("%d\n",(ans.m[0][0]+ans.m[0][1])%mod);
    }  
    return 0;  
}

猜你喜欢

转载自blog.csdn.net/yu121380/article/details/80224785