hdoj.2842 Chinese Rings【矩阵快速幂】 2015/08/21

来源:互联网 发布:美利坚仓储淘宝王无错 编辑:程序博客网 时间:2024/06/05 04:43

Chinese Rings

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


Problem Description
Dumbear likes to play the Chinese Rings (Baguenaudier). It’s a game played with nine rings on a bar. The rules of this game are very simple: At first, the nine rings are all on the bar.
The first ring can be taken off or taken on with one step.
If the first k rings are all off and the (k + 1)th ring is on, then the (k + 2)th ring can be taken off or taken on with one step. (0 ≤ k ≤ 7)

Now consider a game with N (N ≤ 1,000,000,000) rings on a bar, Dumbear wants to make all the rings off the bar with least steps. But Dumbear is very dumb, so he wants you to help him.
 

Input
Each line of the input file contains a number N indicates the number of the rings on the bar. The last line of the input file contains a number "0".
 

Output
For each line, output an integer S indicates the least steps. For the integers may be very large, output S mod 200907.
 

Sample Input
140
 

Sample Output
110
 

Source
2009 Multi-University Training Contest 3 - Host by WHU 

注:f(n) = 2*f(n-2)+f(n-1)+1  矩阵需要定义long long 型,否则会WA
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int mod = 200907;struct node{    long long m[3][3];}p,per;void init(){    int i,j;    for( i = 0 ; i < 3 ; ++i ){        for( j = 0 ; j < 3 ; ++j ){           per.m[i][j] = (i==j);           p.m[i][j] = 0;        }    }    p.m[0][1] = 2;    p.m[0][0] = p.m[1][0] = p.m[0][2] = p.m[2][2] = 1;}node mutil(node a,node b){    node c;    memset(c.m,0,sizeof(c.m));    for( int i = 0 ; i < 3 ; ++i ){        for( int j = 0 ; j < 3 ; ++j ){            if( a.m[j][i] ){                for( int k = 0 ; k < 3 ; ++k ){                    c.m[j][k] += ( a.m[j][i] * b.m[i][k] ) % mod;                    c.m[j][k] %= mod;                }            }        }    }    return c;}int modefy( int k ){    node ans = per , po = p;    while( k ){        if( k&1 ) ans = mutil(ans,po);        po = mutil(po,po);        k >>= 1;    }    return (ans.m[0][0] * 2 + ans.m[0][1] + ans.m[0][2]) % mod;}int main(){    int n,k;    init();    while( ~scanf("%d",&n) , n ){        if( n <= 2 )            printf("%d\n",n);        else printf("%d\n",modefy(n-2));    }    return 0;}


0 0