Hduoj2855【矩阵数学】

来源:互联网 发布:注册的淘宝号怎么注销 编辑:程序博客网 时间:2024/05/23 12:07
/*Fibonacci Check-upTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1257    Accepted Submission(s): 708Problem DescriptionEvery ALPC has his own alpc-number just like alpc12, alpc55, alpc62 etc.As more and more fresh man join us. How to number them? And how to avoid their alpc-number conflicted? Of course, we can number them one by one, but that’s too bored! So ALPCs use another method called Fibonacci Check-up in spite of collision. First you should multiply all digit of your studying number to get a number n (maybe huge).Then use Fibonacci Check-up!Fibonacci sequence is well-known to everyone. People define Fibonacci sequence as follows: F(0) = 0, F(1) = 1. F(n) = F(n-1) + F(n-2), n>=2. It’s easy for us to calculate F(n) mod m. But in this method we make the problem has more challenge. We calculate the formula , is the combination number. The answer mod m (the total number of alpc team members) is just your alpc-number.InputFirst line is the testcase T.Following T lines, each line is two integers n, m ( 0<= n <= 10^9, 1 <= m <= 30000 )OutputOutput the alpc-number.Sample Input21 300002 30000Sample Output13Source2009 Multi-University Training Contest 5 - Host by NUDT Recommendgaojie   |   We have carefully selected several similar problems for you:  1588 2254 1757 2971 2294 */#include<stdio.h>#include<stdlib.h>#include<string.h>int n, m, ans[3][3], temp[3][3];void mul(int a[3][3], int b[3][3], int flag){int temp1[3][3] = {0};//保存中间结果 for(int i = 1; i < 3; ++i)for(int j = 1; j < 3; ++j){for(int k = 1; k < 3; ++k)temp1[i][j] = (temp1[i][j] + a[i][k] * b[k][j]) % m; }if(flag == 1)//更新 {ans[1][1] = temp1[1][1];ans[1][2] = temp1[1][2];ans[2][1] = temp1[2][1];ans[2][2] = temp1[2][2];}else{temp[1][1] = temp1[1][1];temp[1][2] = temp1[1][2];temp[2][1] = temp1[2][1];temp[2][2] = temp1[2][2];}}void matrix_pow(){ans[1][1] = 1; ans[1][2] = 0;ans[2][1] = 0; ans[2][2] = 1;while(n){if(n & 1)mul(ans, temp, 1);mul(temp, temp, 2);n >>= 1;}}int main(){int i, j, k, t;scanf("%d", &t);while(t--){scanf("%d%d", &n, &m);n *= 2;if(n == 0){printf("0\n");continue;}temp[1][1] = 1;temp[1][2] = 1;temp[2][1] = 1;temp[2][2] = 0;matrix_pow();printf("%d\n", ans[1][2] % m); } return 0;} 


题意:给出n和m求公式 的值。

思路:这里有2个难点,第一个就是公式化简,第二个就是斐波那契的矩阵乘法的规律和矩阵的快速幂。先说公式化简吧~下面附上 图片




公式化简以后就要用到斐波那契的矩阵乘法规律:

我们可以先保存b=f(1),a=f(0),然后每次设: b'=a+b a'=b。后利用a'和b'一直循环即可。同时我们可以将b a看做一个向量[b a],前面的操作就可以乘以矩阵:

|1 1|*[b a]=[a+b b]。

|1 0|

也就是说,如果我们要求第100个fibonacci数,只需要将矩阵[1 0]乘上 
1 1 
1 0 
的一百次方,再取出第二项即可。

接着就是矩阵的快速幂了,求出矩阵1  1 的2n次方 就可以得到结果了。

                                                         1  0

难点:首先在于公式的化简,其次就是斐波那契的矩阵求法从而用矩阵快速幂求得结果。

0 0