Queuing
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2859 Accepted Submission(s): 1314
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.
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
Sample Output
6 2 1
//f(n) = f(n-1) + f(n-2) + f(n-4)
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 5;
const int Max = 100001;
int f[Max];
int m,mod;
struct mat
{
long long v[maxn][maxn];
mat()
{
memset(v,0,sizeof(v));
}
};
mat p,receive;
void init() //初始化矩阵
{
int i,j;
f[0] = 2;f[1] = 4;f[2] = 6;f[3] = 9;
p.v[0][0] = p.v[0][2] = p.v[0][3] = p.v[1][0] = p.v[2][1] = p.v[3][2] = 1;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(p.v[i][j])
{
continue;
}
else
{
p.v[i][j] = 0;
}
}
}
}
mat matrix_mul(mat p1,mat p2) //矩阵乘法
{
mat t;
int i,j,k;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(p1.v[i][j])
{
for(k=0;k<4;k++)
{
t.v[i][k] += (p1.v[i][j] * p2.v[j][k]) % mod;
}
}
}
}
return t;
}
mat matrix_mi(mat p,int k) //矩阵快速幂
{
mat t;
for(int i=0;i<4;i++) t.v[i][i] = 1; //单位阵
while(k)
{
if(k & 1)
t = matrix_mul(t,p);
k >>= 1;
p = matrix_mul(p,p);
}
return t;
}
int main()
{
freopen("1.in","r",stdin);
while(cin>>m>>mod)
{
init();
if(m<=4) cout<<f[m-1] % mod;
else
{
receive = matrix_mi(p,m-4);
cout<<(receive.v[0][0] * f[3] + receive.v[0][1] * f[2] + receive.v[0][2] * f[1] + receive.v[0][3] * f[0]) % mod;
}
cout<<endl;
}
return 0;
}

794

被折叠的 条评论
为什么被折叠?



