hdu 2842(矩陣快速冪+遞推),hdu2842

來源:互聯網
上載者:User

hdu 2842(矩陣快速冪+遞推),hdu2842

題意:一個中國環的遊戲,規則是一個木棒上有n個環,第一個環是可以隨意放上或拆下的,剩下的環x如果想放上或拆下必須前一個環x-1是放上的且前x-2個環全部是拆下的,問n個環最少多少次操作可以全部拆掉。
題解:需要進行遞推,首先第一步肯定是要拆第n個環保證操作次數最少,因為後面的環是否存在對前面的環不造成影響,而先拆前面的如果要拆後面的環還是要把前面的放上,f(n)表示拆掉前n個環需要的最少操作次數,先拆第n個要拆前n-2個再拆第n個,花費f(n-2)+1,然後這時是00…0010,要拆第n-1個需要先把前n-2個放上,花費的步數和拆下是一樣是f(n-2),這時就是11…1110,全部拆掉就是f(n-1),因此遞推公式是f(n) = f(n-1) + 2 * f(n-2) + 1。最後矩陣快速冪就行了。

#include <stdio.h>#include <string.h>const int MOD = 200907;struct Mat {    long long g[3][3];}ori, res;long long n;Mat multiply(Mat x, Mat y) {    Mat temp;    for (int i = 0; i < 3; i++)        for (int j = 0; j < 3; j++) {            temp.g[i][j] = 0;            for (int k = 0; k < 3; k++)                temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % MOD;        }    return temp;}void calc(long long n) {    while (n) {        if (n & 1)            ori = multiply(ori, res);        n >>= 1;        res = multiply(res, res);    }}int main() {    while (scanf("%lld", &n) == 1 && n) {        if (n == 1 || n == 2) {            printf("%lld\n", n);            continue;        }        memset(ori.g, 0, sizeof(ori.g));        memset(res.g, 0, sizeof(res.g));        ori.g[0][0] = 2;        ori.g[0][1] = ori.g[0][2] = 1;        res.g[0][0] = res.g[0][1] = res.g[2][0] = res.g[2][2] = 1;        res.g[1][0] = 2;        calc(n - 2);        printf("%lld\n", ori.g[0][0]);    }    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.