东大OJ-1040-Count-快速幂方法求解斐波那契-
2014-07-30 10:36
141 查看
Many ACM team name may be very funny,such as "Complier_Error","VVVVV".Oh,wait for a minute here.Is it "W W"+"V",or "W"+"V V V",or something others we can treat as?There are several ways we can treat this name "VVVVV" (5 'V's),asV V can be treat as a W.For 5 'V's,our have 8 ways.They are:V V V V VV W WW W VV W V VW V WW V V VV V W VV V V WThe problem here is that for n 'V's,how many ways do we have to treat it?Becausethe answer may be too large, you should output the answer module by p.(Ifn is 0,then we have just one way.)
输入
There are multiple test cases. The first line of the input contains an integerM, meaning the number of the test cases.For each test cases, there aretwo integers nand pin a single line.You can assume that0<=n<=2100000000,0<p<=2009.输出
For each test case, output the answer with case number in a single line.样例输入
2 5 5 4 7
样例输出
3
#include<iostream>using namespace std;struct m{int a[2][2]; };m mul(m a, m b,int p){m c;int i, j,k;for (i = 0; i < 2;i++)for (j = 0; j < 2; j++){c.a[i][j] = 0;for (k = 0; k < 2; k++)c.a[i][j] +=( (a.a[i][k] %p)* (b.a[j][k]%p))%p;c.a[i][j] %= p;}return c;}m go(m a, int n,int p){if (n == 1)return a;m b = go(a, n / 2, p);m c = mul(b, b, p);if (n % 2 == 1)c = mul(c, a, p);return c;}int main(){//freopen("in.txt", "r", stdin);int t;cin >> t;m a = { 0, 1, 1, 1 };while (t-- > 0){int n, p;cin >> n >> p;if (n == 0){ cout << 1 << endl; continue; }cout << go(a, n, p).a[1][1]<<endl;}return 0;}[/code]
相关文章推荐
- 东大OJ-1040-Count-快速幂方法求解斐波那契-
- 东大OJ-1040-Count-快速幂方法求解斐波那契-
- [LeetCode-204] Count Primes(0~n 有多少个质数—4种方法求解)
- 三种方法求解Fibonacci(斐波那契)数列
- 三种方法求解Fibonacci(斐波那契)数列
- 数据库性能提高方法1--SET NOCOUNT的用法和注意事项
- 解决mysql 1040错误Too many connections的方法
- 候选码的求解基本方法
- Mysql中count(*),DISTINCT的使用方法和效率研究
- 解决mysql 1040错误Too many connections的方法
- 求解素数几种方法
- 基于并行EBE-CG方法的有限元求解程序(从我的毕业论文中节选出来的)
- Mysql中count(*),DISTINCT的使用方法和效率研究
- 求解:此OracleParameterCollection 的 Count=4 的索引 4 无效 NHibernate
- 用递归和栈的方法实现N皇后求解
- Mysql中count(*),DISTINCT的使用方法和效率研究
- 用oo方法求解24点牌问题
- 用递归方法求解汉诺塔问题
- 【原创】Sql中Count统计记录为0处理方法
- 数列题快速求解方法