HDU - 2842 Chinese Rings

來源:互聯網
上載者:User

標籤:des   style   blog   os   io   for   2014   ar   

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 

題意:給定n個環和規則:如果想取下第n個環那麼要保證前n-2都取下,第n-1還在

思路:設取下第n個環的最短時間是f[n],那麼要想取下第n個環,首先要取下前n-2個即:f[n-2]以及最後一個,所以是

f[n-2]+1, 還有一個第n-1個,要取下它首先要保證第n-2在,所以需要f[n-2](怎麼取下來的怎麼放上去),現在又要取第n-1個了, 綜上所述:f[n] = 2*f[n-2] + f[n-1] + 1, 然後就是構造矩陣了:

不難推出來: | f[n] |              | 1 2 1 |     | f[n-2]|

                       | f[n-1] |    =    | 1 0 0 | *   | f[n-1]|

                       | 1 |                | 0 0 1 |      |    1   |

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;typedef long long ll;const int maxn = 10;const int mod = 200907;int cnt;struct Matrix {int v[maxn][maxn];Matrix() {}Matrix(int x) {init();for (int i = 0; i < maxn; i++) v[i][i] = x;}void init() {memset(v, 0, sizeof(v));}Matrix operator *(Matrix const &b) const {Matrix c;c.init();for (int i = 0; i < cnt; i++)for (int j = 0; j < cnt; j++)for (int k = 0; k < cnt; k++)c.v[i][j] = (c.v[i][j] + (ll)v[i][k]*b.v[k][j]) % mod;return c;}Matrix operator ^(int b) {Matrix a = *this, res(1);while (b) {if (b & 1)res = res * a;a = a * a;b >>= 1;}return res;}} a, b, tmp;int main() {int n;while (scanf("%d", &n) != EOF && n != 0) {if (n < 3) {printf("%d\n", n);continue;}a.init();cnt = 3;a.v[0][0] = a.v[0][2] = a.v[1][0] = a.v[2][2] = 1;a.v[0][1] = 2;tmp = a^(n-2);printf("%d\n", (tmp.v[0][0]*2 + tmp.v[0][1] + tmp.v[0][2]) % mod);}return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.