HDU3519Lucky Coins Sequence(DP+矩陣加速)

bigbigship發表於2014-06-17

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=3519

Problem Description
As we all know,every coin has two sides,with one side facing up and another side facing down.Now,We consider two coins's state is same if they both facing up or down.If we have N coins and put them in a line,all of us know that it will be 2^N different ways.We call a "N coins sequence" as a Lucky Coins Sequence only if there exists more than two continuous coins's state are same.How many different Lucky Coins Sequences exist?
 

Input
There will be sevaral test cases.For each test case,the first line is only a positive integer n,which means n coins put in a line.Also,n not exceed 10^9.
 

Output
You should output the ways of lucky coins sequences exist with n coins ,but the answer will be very large,so you just output the answer module 10007.
 

Sample Input
3 4
 

Sample Output
2 6
分析:我們設f(n)為不滿足條件的個數

若f(n)的後兩位相同 則f(n)=f(n-2); 即在f(n-2)後面加上00或者11;

若f(n-1)的後兩位不同 則f(n)=f(n-1)  即在f(n-1)後面加上0或者1;

因此可得f(n)=f(n-1)+f(n-2);

設g(n) 為符合的個數  則g(n)=2^n-f(n); 化簡成關於g(n)的公式為 g(n)=g(n-1)+g(n-2)+2^(n-2);

程式碼如下:

#include <iostream>
#include <cstring>
using namespace std;
const int mod = 10007;
int n;
struct matrax
{
    int m[4][4];
};
matrax A={
  1,1,0,2,
  1,0,0,0,
  0,1,0,0,
  0,0,0,2
};
matrax E;
void init()
{
   for(int i=0;i<4;i++)
    for(int j=0;j<4;j++)
     E.m[i][j]=(i==j);
}
matrax multi(matrax a,matrax b)
{
    matrax c;
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            c.m[i][j]=0;
            for(int k=0;k<4;k++)
                c.m[i][j]+=a.m[i][k]*b.m[k][j]%mod;
        c.m[i][j]%=mod;
        }
    }
    return c;
}
matrax power(matrax A,int k)
{
    matrax ans=E,p=A;
    while(k){
        if(k&1){
            ans=multi(ans,p);
            k--;
        }
        k>>=1;
        p=multi(p,p);
    }
    return ans;
}
int main()
{
    init();
    int a[4]={8,2,6,16};
    while(cin>>n){
        if(n<=2){
            cout<<0<<endl;
            continue;
        }
        if(n<=5){
            cout<<a[n-2]<<endl;
            continue;
        }
        matrax ans=power(A,n-5);
        int x=0;
        for(int i=0;i<4;i++)
            x+=(ans.m[0][i]*a[4-i-1])%mod;
        cout<<x%mod<<endl;
    }
    return 0;
}


相關文章