HDU 1005

来源:互联网 发布:南京软件学校 编辑:程序博客网 时间:2024/05/17 00:59

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

N很大,有种方法找寻环节,毕竟循环节小于等于49个。

我这里为了用下矩阵乘法的模板,就直接用矩阵加速了。

就是要求

[ab10]n1

快速幂就好啦,最后答案就是base[0][1]+base[1][1]

#include<cstdio> #include<cstring>#include<iostream>using namespace std;typedef long long ll;const int P = 7;const int N=13;ll n,m;struct matrix{    ll a[N][N];    int row,col;    matrix():row(N),col(N){memset(a,0,sizeof(a));}    matrix(int x,int y):row(x),col(y){memset(a,0,sizeof(a));}    ll* operator [] (int x){return a[x];}    matrix operator * (matrix x){        matrix tmp ;        for (int i=0;i<=n+1;i++)            for (int j=0;j<=n+1;j++){                tmp[i][j]=0;                for (int k=0;k<=n+1;k++)                    tmp[i][j]=(tmp[i][j]+a[i][k]*x[k][j])%P;            }        return tmp;    }       void operator *= (matrix x){*this = *this * x;}    matrix operator ^ (ll x){        matrix ret;        for (int i=0;i<=n+1;i++)ret[i][i]=1;        matrix tmp = *this;        for (;x;x>>=1,tmp*=tmp){if(x&1)ret *=tmp;}        return ret;    }};int main(){    int a,b,num;    n=2;    while(cin>>a>>b>>num,(a||b||num)){        matrix base;        base[0][0]=a;base[0][1]=1;base[1][0]=b;base[1][1]=0;        base = base ^ (num-1);        printf("%d\n",(base[0][1]+base[1][1])%7);    }    return 0;} 
0 0