hdu-2604-Queuing

来源:互联网 发布:怎么卸载软件 编辑:程序博客网 时间:2024/04/17 03:43



题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=2604

Queuing



Problem Description
Queues and Priority Queues are data structures which are known to most computer scientists. The Queue occurs often in our daily life. There are many people lined up at the lunch time. 

  Now we define that ‘f’ is short for female and ‘m’ is short for male. If the queue’s length is L, then there are 2L numbers of queues. For example, if L = 2, then they are ff, mm, fm, mf . If there exists a subqueue as fmf or fff, we call it O-queue else it is a E-queue.
Your task is to calculate the number of E-queues mod M with length L by writing a program.
 

Input
Input a length L (0 <= L <= 10 6) and M.
 

Output
Output K mod M(1 <= M <= 30) where K is the number of E-queues with length L.
 

Sample Input
3 84 74 8
 

Sample Output
621
 


题目要求不含101 和111 的串   设f[n]为长度为n串符合条件的个数
则很明显在长度为(n-1)并且符合条件的串后面加上一个0一定符合;如果在长度为n-1的串后面加上一个1的话我们得考虑n-1的串结尾的元素;如果是00的话看做是长度为n-3的串加上100 ;如果是10的话看做长度为n-4的串加上1100
因此f[n]=f[n-1]+f[n-3]+f[n-4]; 根据这个递推式可以构造一个1X4的矩阵和4X4的矩阵相乘得到下一个1X4的矩阵,再用快速幂去算矩阵相乘的结果。


#include<iostream>#include<cstring>#include<iomanip>#include<algorithm>#include<cmath>#include<cstdio>#include<queue>using namespace std;struct Mat{    int ma[33][33];};        int city,n,M;Mat operator * (Mat a,Mat b){    Mat c;    memset(c.ma,0,sizeof(c.ma));    for(int i=0;i<4;i++)    for(int j=0;j<4;j++)    for(int k=0;k<4;k++)    {        c.ma[i][j]+=a.ma[i][k] * b.ma[k][j];        c.ma[i][j]=c.ma[i][j]%M;    }    return c;}Mat operator ^ (Mat a,int k){    Mat c;    for(int i=0;i<4;i++)    for(int j=0;j<4;j++)    {        if(i==j)c.ma[i][j]=1;        else c.ma[i][j]=0;    }    while(k)    {        if(k&1)c=c*a;        a=a*a;        k >>= 1;    }    return c;}int main(){    while(cin>>n>>M)    {        Mat a;        Mat ans;        a.ma[0][0]=a.ma[0][2]=a.ma[0][3]=a.ma[1][0]=a.ma[2][1]=a.ma[3][2]=1;        int i,j;        for(i=0;i<4;i++)        for(j=0;j<4;j++)        {            if(a.ma[i][j]==1)  continue;            a.ma[i][j]=0;        }        ans.ma[0][0]=9;        ans.ma[1][0]=6;        ans.ma[2][0]=4;        ans.ma[3][0]=2;        if(n>3)        {               if(n==4){                cout<<9%M<<endl;                continue;            }            Mat ans1=a^(n-4);            int ans2=0;            for(int s=0;s<4;s++)            ans2=(ans2+ans1.ma[0][s]*ans.ma[s][0])%M;            cout<<ans2<<endl;        }        else if(n!=0)cout<<ans.ma[3-n+1][0]%M<<endl;        else cout<<0%M<<endl;    }    return 0;} 


原创粉丝点击