HDU 2604-Queuing(递推+构造矩阵)

来源:互联网 发布:淘宝上买电脑靠谱吗 编辑:程序博客网 时间:2024/06/08 08:52

Queuing

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5944    Accepted Submission(s): 2591


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
 

Author
WhereIsHeroFrom
 

Source

题意:n个人排队,f表示女,m表示男,包含子串‘fmf’和‘fff’的序列为O队列,否则为E队列,

问你有多少个序列为E队列。

题解:递推公式都是一样的,看别人的题解写的挺好的,就参照一下别人的吧。。。

用f(n)表示n个人满足条件的结果,那么如果最后一个人是m的话,那么前n-1个满足条件即可,就是f(n-1); 
如果最后一个是f那么这个还无法推出结果,那么往前再考虑一位:那么后三位可能是:mmf, fmf, mff, fff,其中fff和fmf不满足题意所以我们不考虑,但是如果是 
mmf的话那么前n-3可以找满足条件的即:f(n-3);如果是mff的话,再往前考虑一位的话只有mmff满足条件即:f(n-4) 
所以f(n)=f(n-1)+f(n-3)+f(n-4),递推会跪,可用矩阵快速幂 ,构造矩阵如下:


#include<map>    #include<stack>    #include<queue>  #include<vector>    #include<math.h>    #include<stdio.h>  #include<iostream>#include<string.h>    #include<stdlib.h>    #include<algorithm>    using namespace std;    typedef long long ll;    #define inf 1000000000    #define mod 1000000007   #define maxn  505#define lowbit(x) (x&-x)    #define eps 1e-10  struct node{ll x[4][4];}a,b,c;int l,m;node q1(node a,node b){node d;int i,j,k;for(i=0;i<4;i++)for(j=0;j<4;j++){d.x[i][j]=0;for(k=0;k<4;k++)d.x[i][j]+=a.x[i][k]*b.x[k][j];d.x[i][j]%=m;}return d;}node q(node a,int b){node d;int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++){if(i==j)d.x[i][j]=1;elsed.x[i][j]=0;}while(b){if(b%2)d=q1(d,a);a=q1(a,a);b/=2;}return d;}int  main(void){a.x[0][0]=9;a.x[1][0]=6;a.x[2][0]=4;a.x[3][0]=2;b.x[0][0]=b.x[0][2]=b.x[0][3]=1;b.x[1][0]=b.x[2][1]=b.x[3][2]=1;while(scanf("%d%d",&l,&m)!=EOF){if(l==0){printf("0\n");continue;}if(l<=4){printf("%lld\n",a.x[4-l][0]%m);continue;}c=q(b,l-4);c=q1(c,a);printf("%lld\n",c.x[0][0]);}return 0;}


原创粉丝点击