您的位置:首页 > 其它

SDAU dp专题 1009

2016-05-05 00:09 369 查看
1:问题描述

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

2:思路

这个题找到递推公式后,要利用矩阵快速幂。

3:感想

挺难的一个题,查的题解~~

要好好研究研究。

4:ac代码

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
int N,m;
struct matrix
{
int a[4][4];
}origin,res;
matrix multiply(matrix x,matrix y)
{
matrix temp;
memset(temp.a,0,sizeof(temp.a));
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<4;k++)
{
temp.a[i][j]+=(x.a[i][k]*y.a[k][j])%m;
temp.a[i][j]%=m;
}
}
}
return temp;
}
void calc(int n)
{
while(n)
{
if(n&1)
res=multiply(res,origin);

origin=multiply(origin,origin);
n>>=1;
}
}
int main()
{
int ff[5]={9,6,4,2};
int i,j;
matrix aaa;
//freopen("r.txt","r",stdin);
while(~scanf("%d%d",&N,&m))
{
if(N==0)
{
cout<<0<<endl;
continue;
}
if(N<=4)
{
cout<<ff[4-N]%m<<endl;
continue;
}
int doudou[5]={0};
memset(origin.a,0,sizeof(origin.a));
memset(aaa.a,0,sizeof(aaa.a));
aaa.a[0][0]=9;
aaa.a[1][0]=6;
aaa.a[2][0]=4;
aaa.a[3][0]=2;
origin.a[0][0]=origin.a[0][2]=origin.a[0][3]=origin.a[1][0]=origin.a[2][1]=origin.a[3][2]=1;
res.a[0][0]=res.a[1][1]=res.a[2][2]=res.a[3][3]=1;
calc(N-4);
res=multiply(res,aaa);
cout<<res.a[0][0]%m<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp