Problem I
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.
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
题意:n个人排队,f表示女,m表示男,包含子串fmf和fff的序列为O队列,否则为E队列,有多少个序列为E队列。
解题思路:刚开始想的简单啊,直接递推公式,但是现实太残酷。用普通方法会超时的,这个星期就想这一个题去了,看了巨巨的博客,才知道还有矩阵这个好东西;具体矩阵怎么用,见我总结的《关于矩阵相乘快速幂的理解及其用处》
感悟:这星期真是堕落。。。。。才做了这么一个题;
代码:
#include
#include
#include
using namespace std;
int n,mod;
struct Matrix{
int
arr[4][4];
};
Matrix unit,init;
//矩阵相乘的函数
Matrix Mul(Matrix a,Matrix b){
Matrix
c;
for(int
i=0;i<4;i++)
for(int j=0;j<4;j++){
c.arr[i][j]=0;
for(int k=0;k<4;k++)
c.arr[i][j]=(c.arr[i][j]+a.arr[i][k]*b.arr[k][j]%mod)%mod;
//cout<<c.arr[i][j]<<endl;
c.arr[i][j]%=mod;
}
return
c;
}
//进行F[n]=F[n-1]+F[n-3]+F[n-4]
Matrix Pow(Matrix a,Matrix b,int k){
while(k){
if(k&1){
b=Mul(b,a);
}
a=Mul(a,a);
//cout<<k<<endl;
k>>=1;//k/=2但是前者快点
}
return
b;
}
//初始化
void Init(){
for(int
i=0;i<4;i++)
for(int j=0;j<4;j++){
init.arr[i][j]=0;
unit.arr[i][j]=0;
}
//递推的前四项
unit.arr[0][0]=9,
unit.arr[0][1]=6,
unit.arr[0][2]=4,
unit.arr[0][3]=2;
//设置递推关系的矩阵
init.arr[0][0]=1,
init.arr[0][1]=1,
init.arr[1][2]=1,
init.arr[2][0]=1,
init.arr[2][3]=1,
init.arr[3][0]=1;
}
int main(){
#include
#include
using namespace std;
int n,mod;
struct Matrix{
};
Matrix unit,init;
//矩阵相乘的函数
Matrix Mul(Matrix a,Matrix b){
}
//进行F[n]=F[n-1]+F[n-3]+F[n-4]
Matrix Pow(Matrix a,Matrix b,int k){
}
//初始化
void Init(){
}
int main(){
}
我每天都在努力,只是想证明我是认真的活着.