HDU - 1005 Number Sequence 矩阵快速幂

HDU - 1005

Number Sequence

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

 

网上的一些解法很多是关于找规律的,其实找规律也是有一些道理的,根据鸽巢原理总会出现一些重复项,所以找到规律以后开始mod就行

但是这种解法毕竟还是有bug,虽然能够AC掉,但也有人提出了Hack数据   HDU数据有点水

其实Hack挺容易,就是针对一个程序,设计一组n,k让它很难找出规律就行

所以这个时候矩阵快速幂就来了~

mod的问题很好解决,我们先来看一下如何构建矩阵

 

     

我们可以假定有一个矩阵K,使得{f(n-1) f(n-2)}与之相乘之后可以得到{f(n) f(n-1)}

由f(n) = (A * f(n - 1) + B * f(n - 2)):

  相乘之后的矩阵可化为{A * f(n - 1) + B * f(n - 2)  f(n-1) }

不难得出矩阵K

所以初始化矩阵ans为

{f(2) f(1)} 即  {1 1} 竖着写也可以我懒得开二维所以直接写了横着的一维数组

构建另一个矩阵K为

{A  1}

{B  0}

如果n的值为1或2,直接返回  注意一定要返回!!!不然n=1,n-=2,n=-1,然后while(-1)  呵呵呵~~~~

否则求A*Kn-2 输出ans[1]的值即可。 为什么是n-2?显然啊,可以自己举个例子,求n=3,要乘1次即可

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int mat[3][3],ans[3];
void Mul(){
    int temp[3];
    for(int i=1;i<=2;i++){
        temp[i]=0;
        for(int k=1;k<=2;k++)
            temp[i]+=(ans[k]*mat[k][i]%7);
        temp[i]%=7;
    }
    memcpy(ans,temp,sizeof(temp));
}
void Mulself(){
    int temp[3][3];
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            temp[i][j]=0;
            for(int k=1;k<=2;k++)
                temp[i][j]+=(mat[i][k]*mat[k][j]%7);
            temp[i][j]%=7;
        }
    }
    memcpy(mat,temp,sizeof(temp));
}
int main(){
    int a,b,c;
    while(~scanf("%d%d%d",&a,&b,&c)){
        if(!b&&!a&&!c)break;
        if(c<= 2){
            printf("1\n");
            continue;
        }
        mat[1][1]=a,mat[1][2]=1;
        mat[2][1]=b;mat[2][2]=0;
        ans[1]=ans[2]=1;
        c-=2;
        while(c){
            if(c&1)Mul();
            Mulself();
            c>>=1;
        }
        printf("%d\n",ans[1]%7);
    }
}

 

posted @ 2020-03-07 11:48  An_Fly  阅读(180)  评论(0编辑  收藏  举报