您的位置:首页 > 产品设计 > UI/UE

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

2017-08-14 11:10 447 查看


Queuing

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 5990    Accepted Submission(s): 2611


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

 

Sample Output

6
2
1

 

题意:

有一个长度为L的队列,由男女组成,分别用字符m和f表示,如果这串字符含有fmf或者含有fff,则该串叫做O-queue,否则该串叫做E-queue.

先给出一个数L为字符串长度,求有m,f组成的E-queue型字符串的个数。

思路:

这是一个和斐波那契数列相似的递推问题,而且公式不好推导。 

设F
为字符串长度为n时,由m,f组成的E-queue型字符串的个数。

首先先分析一下图形 

我们可以倒着考虑 他在第n位有两种情况 f或m 如下图 



第一种情况 当第n位为f时, 为了满足情况n-1 可以为f或者m 两种情况,这两种情况会有不同的结果,如果n-1 为f 那么我们就可以确定n-2, n-3一定为 m 那么第n-4位就可以随便填了 都不会影响结果 后4位就是唯一确定的。前n-4位个数就为 f(n-4), 

同理, 我们看 当n-1位为m的情况,为了满足条件, n-2必须为m 那么n-3位 也可以随便填 后三位确定 那么f(n) 个数再加上 f(n-3)

再看第二种情况。 当第n位为m时 第n-1位 不管填什么都满足条件, 所以f(n)得个数还要加上f(n-1) 的个数可能性

因此得到递推公式 f(n) = f(n-1)+f(n-3)+f(n-4)
但要注意f (4)不满足

然后就是推矩阵……看图



f (n)=f(n-1)+f(n-3)+f(n-4)=1*f(n-1)+0*f(n-2)+1*f(n-3)+1*f(n-4)由此可推出  第一行是 1 0 1 1    剩下的  可同理   

code:

#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int L,mod;
int res[5][5],a[5][5];
int temp[5][5];
void Mul(int a[][5],int b[][5])
{
memset(temp,0,sizeof(temp));
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
for(int k=0;k<4;k++)
temp[i][j]=(temp[i][j]+a[i][k]*b[k][j]%mod)%mod;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
a[i][j]=temp[i][j];
return ;
}
void fun(int n)
{
memset(res,0,sizeof(res));
for(int i=0;i<4;i++)
res[i][i]=1;
while(n){
if(n&1)
Mul(res,a);
Mul(a,a);
n>>=1;
}
return ;
}
int main()
{
int f[5];
f[0]=0;
f[1]=2;
f[2]=4;
f[3]=6;
f[4]=9;
while(~scanf("%d %d",&L,&mod)){
if(L<=4)
printf("%d\n",f[L]%mod);
else{
memset(a,0,sizeof(a));
a[0][0]=a[0][2]=a[0][3]=1;
a[1][0]=a[2][1]=a[3][2]=1;
fun(L-4);
int ans=0;
for(int i=0;i<4;i++){
ans+=res[0][i]*f[4-i]%mod;
}
printf("%d\n",ans%mod);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: