1. 程式人生 > >Chinese Rings (九連環+矩陣快速冪)

Chinese Rings (九連環+矩陣快速冪)

game 百度一 const problem scan make then indicate urn

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2842

題目:

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 題意:給你個n連環(就是平時玩的九連環類的益智玩具,還不知道的就請自行百度一下啦……),問最少要操作多少次才能把所有的環取下來~ 思路:個人認為這是要靠經驗來,沒玩過的可能不知道該怎樣取才能把所有的環都取下來。第n項與前幾項的關系是f(n)=f(n-1)+2*f(n-2) + 1,解釋一下這個遞推公式就是你要取下第n個的話得先把1~n-2都取下來(第一個f(n-2)),第n-1個掛在上面,然後把第n個取下來(遞推公式中1的由來),然後再把1~n-2全部掛上去(第二個f(n-2)),然後就是把第n-1取下去(f(n-1))。因為就可以構造出矩陣了,f[0] = 2, f[1] = 1, f[2] = 1;
a[0][0] = 1, a[0][1] = 1, a[0][2] = 0;
a[1][0] = 2, a[1][1] = 0, a[1][2] = 0;
a[2][0] = 1, a[2][1] = 0, a[2][2] = 1。 代碼實現如下:
 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 typedef long long ll;
 5 const int mod = 200907;
 6 int n;
 7 int f[3], a[3][3];
 8 
 9 void mul(int f[3], int a[3][3]) {
10     int c[3];
11     memset(c, 0, sizeof(c));
12     for(int i = 0; i < 3; i++) {
13         for(int j = 0; j < 3; j++) {
14             c[i] = (c[i] + (ll) f[j] * a[j][i]) % mod;
15         }
16     }
17     memcpy(f, c, sizeof(c));
18 }
19 
20 void mulself(int a[3][3]) {
21     int c[3][3];
22     memset(c, 0, sizeof(c));
23     for(int i = 0; i < 3; i++) {
24         for(int j = 0; j < 3; j++) {
25             for(int k = 0; k < 3; k++) {
26                 c[i][j] = (c[i][j] + (ll) a[i][k] * a[k][j]) % mod;
27             }
28         }
29     }
30     memcpy(a, c, sizeof(c));
31 }
32 
33 int main() {
34     while(~scanf("%d", &n) && n) {
35         if(n == 1) {
36             printf("1\n");
37             continue;
38         }
39         if(n == 2) {
40             printf("2\n");
41             continue;
42         }
43         f[0] = 2, f[1] = 1, f[2] = 1;
44         a[0][0] = 1, a[0][1] = 1, a[0][2] = 0;
45         a[1][0] = 2, a[1][1] = 0, a[1][2] = 0;
46         a[2][0] = 1, a[2][1] = 0, a[2][2] = 1;
47         n = n - 2;
48         for(; n; n >>= 1) {
49             if(n & 1) mul(f, a);
50             mulself(a);
51         }
52         printf("%d\n", f[0] % mod);
53     }
54     return 0;
55 }

Chinese Rings (九連環+矩陣快速冪)