hdu 4291 A Short problem

本文介绍了一种利用矩阵连乘原理解决循环节查找问题的方法,通过代码实现详细解释了算法步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=4291

找循环节 + 矩阵连乘

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>

#define LL long long
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const LL MOD=1000000007;
const LL K1=222222224;
const LL K2=183120;
LL a[2][2];
LL ans[2];
void Renew(LL M)
{
    LL temp[2];
    temp[0]=(ans[0]*a[0][0])%M+(ans[1]*a[1][0])%M;
    temp[1]=(ans[0]*a[0][1])%M+(ans[1]*a[1][1])%M;
    ans[0]=temp[0]%M;
    ans[1]=temp[1]%M;
}
void Kmul(LL M)
{
    LL temp[2][2];
    temp[0][0]=(a[0][0]*a[0][0])%M+(a[0][1]*a[1][0])%M;
    temp[0][1]=(a[0][0]*a[0][1])%M+(a[0][1]*a[1][1])%M;
    temp[1][0]=(a[1][0]*a[0][0])%M+(a[1][1]*a[1][0])%M;
    temp[1][1]=(a[1][0]*a[0][1])%M+(a[1][1]*a[1][1])%M;
    a[0][0]=temp[0][0]%M;a[0][1]=temp[0][1]%M;
    a[1][0]=temp[1][0]%M;a[1][1]=temp[1][1]%M;
}
LL Save(LL n,int M)
{
    a[0][0]=3;a[0][1]=1;
    a[1][0]=1;a[1][1]=0;
    ans[0]=1;ans[1]=0;
    while(n)
    {
        if(n&1)
        {
            Renew(M);
        }
        Kmul(M);
        n=n>>1;
    }
    n=ans[1];
    return n;
}
int main()
{
    //freopen("data.txt","r",stdin);
    LL n;
    while(cin>>n)
    {
      cout<<Save(Save(Save(n,K2),K1),MOD)<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/liulangye/archive/2012/09/20/2695837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值