ACM_HDUOJ_2604_Queuing排队问题
2016-07-19 12:02
381 查看
Queuing
[b]Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4554 Accepted Submission(s): 2002
[/b]
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
Input a length L (0 <= L <= 10
6) and M.
[align=left]Output[/align]
Output K mod M(1 <= M <= 30) where K is the number of E-queues with length L.
[align=left]Sample Input[/align]
3 8
4 7
4 8
[align=left]Sample Output[/align]
6
2
1问题描述 两个参数L(队列的长度)和M(结果对M取余)。计算队列中不含有fff且不含有fmf的队列个数对M取余。问题分析 l=0->0;l=1->2;l=2->4;l=3->6;l=4->9;l=5->15; 找规律可知F(l)=F(l-1)+F(l-3)+F(l-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)|F(n)是矩阵|1,0,1,1|的(n-4)次幂与矩阵|F(4)|相乘的第一行第一列元素 |1,0,0,0| |F(3)| |0,1,0,0| |F(2)| |0,0,1,0| |F(1)|用快速幂对矩阵求n次幂即可;AC代码
#include <cmath> #include<iostream> //#include<algorithm> #include<cstring> using namespace std; int m; struct Matrix{ long long int m_matrix[4][4]; Matrix operator*(const Matrix& rhs)const{ Matrix temp; for(int i = 0 ; i < 4 ; i++){ for(int j = 0 ; j < 4 ; j++){ temp.m_matrix[i][j] = 0; for(int k = 0 ; k < 4 ; k++){ temp.m_matrix[i][j] += (m_matrix[i][k])*(rhs.m_matrix[k][j])%m; temp.m_matrix[i][j] %= m; } } } return temp; } }; int get(int l){ int n =l- 4; Matrix rhs={ 1,0,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0}; Matrix ans; memset(ans.m_matrix , 0 , sizeof(ans.m_matrix)); for(int i = 0 ; i < 4 ; i++) ans.m_matrix[i][i] = 1; while(n){ if(n&1) ans = ans*rhs; n >>= 1; rhs = rhs*rhs; } int sum = 0; sum += ans.m_matrix[0][0]*9%m; sum += ans.m_matrix[0][1]*6%m; sum += ans.m_matrix[0][2]*4%m; sum += ans.m_matrix[0][3]*2%m; return sum%m; } int main() { int l,s; while(cin>>l>>m){ switch(l){ case 0:s=0;break; case 1:s=2;break; case 2:s=4;break; case 3:s=6;break; case 4:s=9;break; default:break; } if(l>=5){ s=get(l); } cout<<s%m<<endl; } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 用批处理解决数学问题的代码第1/4页
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析