hdu 6050 Funny Function (构造矩阵)

来源:互联网 发布:免费外汇交易软件 编辑:程序博客网 时间:2024/05/21 17:15

Function Fx,yFx,ysatisfies: 

For given integers N and M,calculate Fm,1Fm,1 modulo 1e9+7. 
Input
There is one integer T in the first line. 
The next T lines,each line includes two integers N and M . 
1<=T<=10000,1<=N,M<2^63. 
Output
For each given N and M,print the answer in a single line. 
Sample Input
22 23 3
Sample Output
233



#include <iostream>#include <string.h>#include <stdio.h>using namespace std;typedef long long LL;const int N = 2;const int MOD = 1000000007;struct Matrix{    LL m[N][N];};Matrix I = {//I主对角线是1       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 sub(Matrix a,Matrix b){    Matrix c;    for(int i=0;i<N;i++)    {        for(int j=0;j<N;j++)        {        c.m[i][j] = a.m[i][j] - b.m[i][j] % MOD;        }    }    return c;}Matrix power(Matrix A,LL k)//矩阵A的k次幂(快速幂){    Matrix ans = I,p = A;    while(k)    {        if(k&1)        {            ans = multi(ans,p);            k--;        }        k >>= 1;        p = multi(p,p);    }    return ans;}void show(Matrix a){    for(int i=0;i<N;i++)    {        for(int j=0;j<N;j++)            cout<<a.m[i][j]<<" ";        cout<<endl;    }}int main(){    int t;Matrix A = {       0,1,       2,1};Matrix B1 = {       1,0,       0,1};Matrix B2 = {       -1,1,       2,0};    scanf("%d",&t);    LL n,m;    while(t--)    {        scanf("%lld%lld",&n,&m);        Matrix ans = power(A,n);        Matrix B;        if(n&1)            B=sub(ans,B2);        else            B=sub(ans,B1);        Matrix anss=power(B,m-1);        //show(anss);        LL finalans=((anss.m[0][0]+anss.m[0][1])%MOD+MOD)%MOD;        printf("%lld\n",finalans);    }    return 0;}