HDU2604 Queuing

http://acm.hdu.edu.cn/showproblem.php?pid=2604


 

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.

题意:长度为n的队列,每一位是f或m,求n长度不含fmf和fff的队列可能个数。

思路:自己开始时考虑2^n-含那两种的个数,但是含的比不含要难求。含的要考虑前含&&后不含,前不含&&后含,前含&&后含,而不含只有前不含&&后不含一种情况。

考虑不含的情况,设f(n)为前n位不含的组合数。若最后一位是m,转化为f(n-1),

若最后一位是f,那么最后三位:fff,fmf,mmf,mff,

fff和fmf是不满足的,mmf转化为f(n-3),mff的话,倒数第四位不能是f只能是m,即mmff,转化为f(n-4)

故f(n)=f(n-1)+f(n-3)+f(n-4)。

转化为矩阵即为:  
1 0 1 1       F(N-1) =F(N)     
1 0 0 0  *    F(N-2) = F(N-1)   
0 1 0 0       F(N-3) =F(N-2)
0 0 1 0       F(N-4) =F(N-3)

#include<bits/stdc++.h>
using namespace std;

int n,mod;
struct mat{
	int a[4][4];
};

mat mul(mat x,mat y)
{
	mat res={0};
	for(int i=0;i<4;i++)
		for(int j=0;j<4;j++)
			for(int k=0;k<4;k++)
				res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%mod;
	return res;
}

int pow(int n)
{
	mat c={0},res={0};
	c.a[0][0]=1;
	c.a[0][2]=1;
	c.a[0][3]=1;
	c.a[1][0]=1;
	c.a[2][1]=1;
	c.a[3][2]=1;
	for(int i=0;i<4;i++)res.a[i][i]=1;
	while(n)
	{
		if(n&1)res=mul(res,c);
		c=mul(c,c);
		n=(n>>1);
	}
	return (9*res.a[0][0]+6*res.a[0][1]+4*res.a[0][2]+2*res.a[0][3])%mod;
}

int main()
{
	//freopen("input.in","r",stdin);
	while(cin>>n>>mod)
	{
		if(n==0)cout<<0<<endl;
		else if(n==1)cout<<2%mod<<endl;
		else if(n==2)cout<<4%mod<<endl;
		else if(n==3)cout<<6%mod<<endl;
		else if(n==4)cout<<9%mod<<endl;
		else cout<<pow(n-4)<<endl;
	}
	return 0;
}


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值