Hdoj.4291 A Short problem【矩阵快速幂+循环节处理】 2015/12/09

A Short problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2384    Accepted Submission(s): 834


Problem Description
  According to a research, VIM users tend to have shorter fingers, compared with Emacs users.
  Hence they prefer problems short, too. Here is a short one:
  Given n (1 <= n <= 10 18), You should solve for 
g(g(g(n))) mod 10 9 + 7

  where
g(n) = 3g(n - 1) + g(n - 2)

g(1) = 1

g(0) = 0

 

Input
  There are several test cases. For each test case there is an integer n in a single line.
  Please process until EOF (End Of File).
 

Output
  For each test case, please print a single line with a integer, the corresponding answer to this case.
 

Sample Input
  
  
0 1 2
 

Sample Output
  
  
0 1 42837
 

Source
 

矩阵快速幂,不过需要先找出三个循环节。。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

long long p[3] = {183120,222222224,1000000007},MOD;

struct Matrax{
    long long m[2][2];
}A,per;

void f(){
    A.m[0][0] = 3;
    A.m[0][1] = A.m[1][0] = 1;
    A.m[1][1] = 0;
    per.m[0][0] = per.m[1][1] = 1;
    per.m[0][1] = per.m[1][0] = 0;
}

Matrax Multi(Matrax a,Matrax b){
    Matrax c;
    for( int i = 0 ; i < 2 ; ++i ){
        for( int j = 0 ; j < 2 ; ++j ){
            c.m[i][j] = 0;
            for( int k = 0 ; k < 2 ; ++k ){
                if( !a.m[i][k] || !b.m[k][j] ) continue;
                c.m[i][j] += ( a.m[i][k] * b.m[k][j] ) % MOD;
            }
            c.m[i][j] %= MOD;
        }
    }
    return c;
}

long long Power(long long k){
    Matrax ans=per,s=A;
    while(k){
        if( k&1 ) ans = Multi(ans,s);
        s = Multi(s,s);
        k >>= 1;
    }
    return ans.m[0][0];
}

int main(){
    long long n,ret;
   // f();
    while( ~scanf("%lld",&n) ){
        if( !n ) printf("0\n");
        else {
            f();
            for( int i = 0 ; i < 3 ; ++i ){
                MOD = p[i];
                ret = Power(n-1);
                n = ret==0?MOD:ret;
            }
            printf("%lld\n",n%MOD);
        }
    }
    return 0;
}


找循环节:

#include<stdio.h>

//#define mod 1000000007
#define mod 222222224

int main(){
    long long i,a=1,b=0,t;
    for( i = 2 ; ; ++i ){
        t = ( 3*a+b ) % mod;
        b = a;
        a = t;
        if( a == 1 && b == 0 ){
            printf("%lld\n",i);
            break;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值