HDU 6030 Happy Necklace

來源:互聯網
上載者:User

標籤:cto   target   推導   核心   code   clu   ons   ring   i++   

題目:http://acm.hdu.edu.cn/showproblem.php?pid=6030

題意:給出紅藍兩種,然後排成一個字串,要求在每一個長度為素數的區間裡面是的r(red)的數量不小與b(blue)的數量;

解法:痛點在於如何找規律。容易推知只要長度為2或3的字串滿足r>=b,那麼之後的素數(5、7......)都會滿足r>=b。

假設現在有一個n字元的串,其方案數為f(n),考慮一下能否從f(n-1)推得f(n)?

情況1.如果這個串最後一個字元是r,那麼倒數第二個既可以是r也可以是b。所以此時f(n) = f(n-1).

情況2.如果這個串最後一個字元是b,那麼倒數第二個一定是r才可以滿足“長度為2且r>=b”的條件,那麼倒數第三個就一定是r,否則不滿足“長度為3且r>=b”的條件。所以此時f(n) = f(n-3)

綜上,可得f(n) = f(n-1) + f(n-3).

由於輸入量巨大(1018),所以用數組儲存遞推結果是不可行的,而每次遞推又太慢,所以只能用矩陣快速冪來解決。

由於遞推式中出現f(n-3),所以傳遞矩陣一定是3*3的。

經過推導可得傳遞矩陣為

1 1 0

0 0 1

1 0 0

AC:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <vector>using namespace std;typedef long long ll;const ll m = 1000000000+7;const int N = 4;struct mar{    ll a[N][N];};//結構化矩陣mar mul(mar x,mar y){    mar temp;    for(int i = 1 ; i < N ; i++)        for(int j = 1 ; j < N ; j++)        temp.a[i][j] = 0;    for(int i = 1 ; i < N ; i++)        for(int j = 1 ; j < N ; j++)                for(int k = 1 ; k < N ; k++)                    temp.a[i][j] += (x.a[i][k]%m*y.a[k][j]%m)%m;    return temp;}//矩陣乘法mar quickpow(mar a,ll n){    mar res;    res.a[1][1] = 1; res.a[1][2] = 0; res.a[1][3] = 0;    res.a[2][1] = 0; res.a[2][2] = 1; res.a[2][3] = 0;    res.a[3][1] = 0; res.a[3][2] = 0; res.a[3][3] = 1;//初始化為單位矩陣    while(n)    {        if(n&1) res = mul(res,a);        a = mul(a,a);        n>>=1;    }    return res;}//矩陣快速冪核心代碼int main(){    int t;    ll n;    cin >> t;    while(t--)    {        cin >> n;        if(n==2) {cout << 3 <<endl;continue;}        mar A;        A.a[1][1] = 1; A.a[1][2] = 0; A.a[1][3] = 1;        A.a[2][1] = 1; A.a[2][2] = 0; A.a[2][3] = 0;        A.a[3][1] = 0; A.a[3][2] = 1; A.a[3][3] = 0;//構造傳遞矩陣        mar res = quickpow(A,n-2);        cout <<  ((res.a[1][1] + res.a[1][2] + res.a[1][3]) % m+ (res.a[2][1] + res.a[2][2] + res.a[2][3]) % m+(res.a[3][1] + res.a[3][2] + res.a[3][3]) % m)%m <<endl;    }    return 0;}

 

HDU 6030 Happy Necklace

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.