HDU3519Lucky Coins Sequence(DP+矩阵加速)

来源:互联网 发布:淘宝卖家怎么提升等级 编辑:程序博客网 时间:2024/06/03 14:09

题目链接: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
34
 

Sample Output
26
分析:我们设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;}


1 0
原创粉丝点击