nyist 301 递推求值(矩阵快速幂)

题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=301

思路:注意矩阵乘法不满足交换律,所以要注意初始矩阵在右边,要进行快速幂的矩阵在左边

左边的矩阵为    右边的矩阵为

b a c f2 0 0

1 0 0 f1 0 0

0 0 1  1 0 0

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long ll;
const int maxn = 40000;
const int mod = 1000007;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
struct node
{
    ll a[3][3];
};
node matrixmul(node a,node b)
{
    node c;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            c.a[i][j] = 0;
            for(int k=0; k<3; k++)
            {
                c.a[i][j] += a.a[i][k] * b.a[k][j];
                c.a[i][j] %= mod;
            }
        }
    }
    return c;
}
node quickmod(node s,int k)
{
    node ans;
    memset(ans.a,0,sizeof(s.a));
    ans.a[0][0]=ans.a[1][1]=ans.a[2][2]=1;//初始化为单位矩阵,值不变
    while(k)
    {
        if(k & 1)
            ans = matrixmul(ans,s);
        k = k >> 1;
        s = matrixmul(s,s);
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int f1,f2,d,e,f,n;
        scanf("%d%d%d%d%d%d",&f1,&f2,&d,&e,&f,&n);
        if(n == 1)
        {
             printf("%d\n",(f1+mod)%mod);
             continue;
        }
        if(n == 2)
        {
            printf("%d\n",(f2+mod)%mod);
            continue;
        }
        node sa;
        memset(sa.a,0,sizeof(sa.a));
        sa.a[0][0]=e;
        sa.a[0][1]=d;
        sa.a[0][2]=f;
        sa.a[1][0]=1;
        sa.a[2][2]=1;
        sa = quickmod(sa,n-2);
        node sb;
        memset(sb.a,0,sizeof(sb.a));
        sb.a[0][0]=f2;
        sb.a[1][0]=f1;
        sb.a[2][0]=1;
        sb = matrixmul(sa,sb);//注意顺序
        ll ans = (sb.a[0][0]+mod)%mod;
        printf("%I64d\n",ans);
    }
    return 0;
}


大神地址:http://www.lxway.com/146981016.htm



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值