Chinese Rings hdu 2842 矩阵快速幂

Chinese Rings

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


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
1
4
0
 

 

Sample Output
1
10
 
 
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 #include <math.h>
 5 #include <string.h>
 6 #include <set>
 7 #include <queue>
 8 using namespace std;
 9 #define ll long long
10 typedef struct matrix
11 {
12     ll a[5][5];
13 } matrix;
14 matrix origin,res;
15 matrix multiply(matrix x,matrix y)
16 {
17     matrix temp;
18     memset(temp.a,0,sizeof(temp.a));
19     for(int k=0; k<3; k++)
20         for(int i=0; i<3; i++)
21         if(x.a[i][k])
22             for(int j=0; j<3; j++)
23             {
24                 temp.a[i][j]+=x.a[i][k]*y.a[k][j]%200907;
25                 temp.a[i][j]%=200907;
26             }
27     return temp;
28 }
29 void calc(int n)
30 {
31     memset(res.a,0,sizeof(res.a));
32     for(int i=0; i<3; i++)res.a[i][i]=1;
33     while(n)
34     {
35         if(n&1)res=multiply(res,origin);
36         n>>=1;
37         origin=multiply(origin,origin);
38     }
39 }
40 void init()
41 {
42     memset(origin.a,0,sizeof(origin.a));
43     origin.a[0][0]=origin.a[0][2]=origin.a[1][0]=origin.a[2][2]=1;
44     origin.a[0][1]=2;
45 }
46 int main()
47 {
48     int n;
49     while(scanf("%d",&n),n)
50     {
51         if(n<=2)
52         {
53             printf("%d\n",n);
54             continue;
55         }
56         init();
57         calc(n-2);
58         int ans=0;
59         ans=res.a[0][0]*2%200907+res.a[0][1]%200907+res.a[0][2]%200907;
60         printf("%d\n",ans%200907);
61     }
62 }
View Code

 

转载于:https://www.cnblogs.com/ERKE/p/3838386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值