hdu---(2604)Queuing(矩阵快速幂)

时间:2023-03-10 04:47:10
hdu---(2604)Queuing(矩阵快速幂)

Queuing

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

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.
hdu---(2604)Queuing(矩阵快速幂)
  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
Author
WhereIsHeroFrom
   首先我们不考虑去模的问题:
      l = 0                            0 种
      l = 1      e的数目有 f,m: 2 种
      l = 2        ...........ff,mm,fm,mf    4种
      l = 3                                         6
      l = 4                                        9
      l =  5                                       15
      l  =  6                                      25
      f5=f4+f3+f1;
      f6=f5+f4+f2;
  ------->  fn={   fn-1+fn-3+fn-4  n>4;
由齐次方程构造矩阵.....
|fn   |    |1,0,1,1|  |fn-1|
|fn-1|    |1,0,0,0|  |fn-2|
|fn-2| = |0,1,0,0|*|fn-3|
|fn-3|    |0,0,1,0|   |fn-4|
代码:
 //#define LOCAL
#include<cstdio>
#include<cstring>
using namespace std;
//matrix --> ¾ØÕó
int mat[][];
int ans[][];
int len,m; void init()
{
int cc[][]={
{,,,},{,,,},
{,,,},{,,,}}; for(int i=;i<;i++)
{
for(int j=;j<;j++)
{
mat[i][j]=cc[i][j];
if(i==j) ans[i][j]=;
else ans[i][j]=;
}
}
}
void Matrix(int a[][],int b[][]) //¾ØÕóÏà³Ë
{
int i,j,k;
int c[][]={};
for(j=;j<;j++){
for(i=;i<;i++){
for(k=;k<;k++){
c[j][i]=(c[j][i]+a[j][k]*b[k][i])%m;
}
}
} for(j=;j<;j++)
for(i=;i<;i++)
a[j][i]=c[j][i]; } void pow(int n)
{
while(n>)
{
if(n&) Matrix(ans,mat);
n>>=;
if(n==) break;
Matrix(mat,mat);
}
}
int main()
{
#ifdef LOCAL
freopen("test.in","r",stdin);
#endif
int f[]={,,,};
while(scanf("%d%d",&len,&m)!=EOF)
{
if(len==)printf("%d\n",);
else if(len<=)printf("%d\n",f[len-]%m);
else{
init();
pow(len-);
printf("%d\n",(ans[][]*f[]+ans[][]*f[]+ans[][]*f[]+ans[][]*f[])%m);
}
}
return ;
}