hdu2604 Queuing

Queuing

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


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.
 

 

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 8
4 7
4 8
 

 

Sample Output
6
2
1

 

可以看成只有0 1 串的字符串,长度为n的字符串中子串中不出现101 和111这两个的总数量有多少。然后求模m

恨容易推出an = an-1+an-3+an-4,然后m是一个不变的话,就可以直接循环遍历了。但m是个变量。

由于an = an-1+an-3+an-4 ,所以可以得到:

an      1    0   1  1    an-1

an-1      1    0   0    0    an-2

an-2     =       0    1   0    0     *        an-3

an-3         0    0   1  0      an-4

 

得到公式就好写了。

 1 // a[n] = a[n-1]+a[n-3]+a[n-4];
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 int n, m;
 5 struct mat{
 6     int m[4][4];
 7     mat() {
 8         memset(m, 0, sizeof(m));
 9     }
10 };
11 mat mul(mat &A, mat &B) {
12     mat C;
13     for(int i = 0; i < 4; i ++) {
14         for(int j = 0; j < 4; j ++) {
15             for(int k = 0; k < 4; k ++) {
16                 C.m[i][j] = (C.m[i][j] + A.m[i][k]*B.m[k][j]) % m;
17             }
18         }
19     }
20     return C;
21 }
22 mat pow(mat A, int n){
23     mat B;
24     for(int i = 0; i < 4; i ++) B.m[i][i] = 1;
25     while(n) {
26         if(n&1) B = mul(B,A);
27         A = mul(A,A);
28         n >>= 1;
29     }
30     return B;
31 }
32 int main() {
33     while(cin >> n >> m) {
34         mat A;
35         if(n==0) printf("%d\n",1%m);
36         else if(n==1) printf("%d\n",2%m);
37         else if(n==2) printf("%d\n",4%m);
38         else if(n==3) printf("%d\n",6%m);
39         else {
40             A.m[0][0] = A.m[0][2] = A.m[0][3] = 1;
41             A.m[1][0] = A.m[2][1] = A.m[3][2] = 1;
42             A = pow(A,n-3);
43             int ans = A.m[0][0]*6+A.m[0][1]*4+A.m[0][2]*2+A.m[0][3];
44             printf("%d\n",ans%m);
45         }
46     }
47     return 0;
48 }

 

转载于:https://www.cnblogs.com/xingkongyihao/p/8999876.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值