Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8207 Accepted Submission(s): 3593
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 8
4 7
4 8
4 7
4 8
Sample Output
6
2
1
2
1
题意:一个长度为L的串,只能由f和m组成,且子串中不能出现fff和fmf,输出有几种组合方式
解题思路:对于f(n),如果该串最后一个字母是m,那么前面n-1个字母组成的串只要符合组合方式即可,那么+f(n-1),如果最后一个字母是f,最后三个字母能组成mmf,mff才有可能符合组合方式,mmf对于他前面n-3个字母同样只要满足组合方式就行,+f(n-3),对于mff,前面一个字母肯定不能是f,那么就是最后四个字母为mmff,对于前面n-4个字母满足组合方式即可,+f(n-4),至此推出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
建立初始矩阵
f(1)
f(2)
f(3)
f(4)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define INF 0X3f3f3f3f
const ll MAXN = ;
// const ll mod = 10000;
int mod;
//矩阵的大小 模数
ll n;
struct MAT
{
int mat[MAXN][MAXN];
MAT operator*(const MAT &a) const
{
//重载矩阵乘法
MAT b;
memset(b.mat, , sizeof(b.mat));
for (int i = ; i < MAXN; i++)
{
for (int j = ; j < MAXN; j++)
{
for (int k = ; k < MAXN; k++)
b.mat[i][j] = (b.mat[i][j] + mat[i][k] * a.mat[k][j]);
b.mat[i][j] += mod;
b.mat[i][j] %= mod;
}
}
return b;
}
} start, ans;
MAT Mqpow(MAT base, int b)
{
MAT r;
memset(r.mat, , sizeof(r.mat));
r.mat[][] = , r.mat[][] = , r.mat[][] = , r.mat[][] = ;
//初始状态
while (b)
{
if (b & )
r = base * r;
base = base * base;
b >>= ;
}
return r;
}
int main()
{ start.mat[][] = , start.mat[][] = , start.mat[][] = , start.mat[][] = ;
start.mat[][] = , start.mat[][] = , start.mat[][] = , start.mat[][] = ;
start.mat[][] = , start.mat[][] = , start.mat[][] = , start.mat[][] = ;
start.mat[][] = , start.mat[][] = , start.mat[][] = , start.mat[][] = ;
//建立转移矩阵
int f[] = {, , , , };
while (~scanf("%d%d", &n, &mod))
{
if (n <= )
printf("%d\n", f[n] % mod);
else
printf("%d\n", Mqpow(start, n - ).mat[][]);
}
return ;
}