Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2773 Accepted Submission(s): 1275
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 2 L 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.

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 2 L 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
复制代码
1
2
3
4
5
6
73 8 4 7 4 8
Sample Output
复制代码
1
2
3
4
5
6
76 2 1
记答案为f[n],则易得f[0]=0,f[1]=2,f[2]=4,f[3]=6;f[[4]=9;
当长度为N时,若最后一个字符为M,前N-1个字符没有限制,即为F(N-1);
当最后一个字符串为F的时候,就必须去除最后3个字符是fmf和fff的情况(倒数第二个字符为F、M均有可能会不满足情况),此时最后3个字符可能为mmf和mff;
当后3个字符为mmf时,前N-3个字符没有限制,即F(N-3);
但是当最后四个字符为mmff时,前N-4个字符无限制,即为F(N-1);
即f[n]=f[n-1]+f[n-3]+f[n-4];
转化为矩阵即为:1 0 1 1 F(N-1) F(N) (即是f[n]=1*f[n-1]+0*f[n-2]+1*f[n-3]+1*f[n-4];)
1 0 0 0 * F(N-2) = F(N-1) (下面为单位矩阵)
0 1 0 0 F(N-3) F(N-2)
0 0 1 0 F(N-4) F(N-3)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76#include"iostream" #include"stdio.h" #include"string.h" #include"algorithm" #include"queue" #include"vector" using namespace std; #define N 4 #define LL __int64 struct Mat { LL mat[N][N]; }; int M,n=4; int p[5]={0,2,4,6,9}; Mat operator *(Mat a,Mat b) { int i,j,k; Mat c; memset(c.mat,0,sizeof(c.mat)); for(i=0;i<n;i++) { for(j=0;j<n;j++) { c.mat[i][j]=0; for(k=0;k<n;k++) { c.mat[i][j]+=(a.mat[i][k]*b.mat[k][j])%M; } c.mat[i][j]%=M; } } return c; } int fun(Mat &a,int k) { int i; Mat ans; memset(ans.mat,0,sizeof(ans.mat)); for(i=0;i<n;i++) ans.mat[i][i]=1; while(k) { if(k&1) ans=ans*a; k>>=1; a=a*a; } LL s=0; for(i=0;i<n;i++) { s+=ans.mat[0][i]*p[n-i]; s%=M; } return s; } int main() { int i,l; Mat a; while(scanf("%d%d",&l,&M)!=-1) { if(l<=n) { printf("%dn",p[l]%M); continue; } memset(a.mat,0,sizeof(a.mat)); a.mat[0][0]=a.mat[0][2]=a.mat[0][3]=1; for(i=1;i<n;i++) a.mat[i][i-1]=1; printf("%dn",fun(a,l-4)); } return 0; }
最后
以上就是甜美月光最近收集整理的关于hdu 2604 Queuing (矩阵快速幂) Queuing的全部内容,更多相关hdu内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复