HDU 2604-Queuing

来源:互联网 发布:java项目感想总结 编辑:程序博客网 时间:2024/04/30 01:39


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

F[0] = 0 , F[1] = 2 , F[2] = 4 , F[3] = 6 , F[4] = 9 , F[5] = 15

n >= 5  F[n] = F[n-1]+F[n-3]+F[n-4]

得到的矩阵是:

  0 1 0 0

  0 0 1 0

  0 0 0 1

  1 1 0 1

CODE:

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#include <string>#include <stack>#include <queue>#include <vector>#include <set>#include <map>typedef long long ll;const int inf=0xffffff;using namespace std;typedef vector<int> vec;typedef vector<vec> mat;int K,M;mat mul(mat &A,mat &B){    mat C(A.size(),vec(B[0].size()));    for(int i=0;i<A.size();i++)    {        for(int k=0;k<B.size();k++)        {            for(int j=0;j<B[0].size();j++)            {                C[i][j] = (C[i][j] + A[i][k]*B[k][j])%M;            }        }    }    return C;}mat pow(mat A){    mat B(A.size(),vec(A.size()));    for(int i=0;i<4;i++)        B[i][i]=1;    int n=K-4;    while(n > 0)    {        if(n & 1) B = mul(B, A);        A = mul(A, A);        n >>= 1;    }    return B;}int main(){    //freopen("in.in","r",stdin);    int f[5];    f[0]=2;f[1]=4;f[2]=6;f[3]=9;    while(~scanf("%d %d",&K,&M))    {        mat A(4,vec(4));        A[0][1]=1;A[1][2]=1;A[2][3]=1;        A[3][0]=1;A[3][1]=1;A[3][3]=1;        A = pow(A);        ll ans=0;        for(int i=0;i<4;i++)        {            ans +=(ll) (A[3][i]*f[i])%M;        }        if(K <= 4) printf("%d\n",f[K-1]%M);        else printf("%I64d\n",ans%M);    }    return 0;}


0 0
原创粉丝点击