poj 3070 Fibonacci (矩阵加速线性递推式)

题目链接

题意:求f[n] % 10000,f为斐波那契数。

思路:按照题目给出的公式,或者按照加速线性递推式的方法都可以。。。

因为把模数的1E4手滑写成1E4+7结果调了半天也是没谁了呵呵呵呵。

/* ***********************************************
Author :111qqz
Created Time :Tue 18 Oct 2016 01:18:40 AM CST
File Name :code/poj/3070.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int MOD = 1E4;
 7int n;
 8struct Mat
 9{
10    int mat[5][5];
1    void clear()
2    {
3	ms(mat,0);
4    }
 1}M,M1;
 2Mat operator * (Mat a,Mat b)
 3{
 4    Mat c;
 5    c.clear();
 6    for ( int i = 0 ; i < 2 ; i++)
 7	for ( int j = 0 ; j < 2 ; j++)
 8	    for ( int k = 0 ; k < 2 ; k++)
 9		c.mat[i][j] = (c.mat[i][j] + a.mat[i][k]*b.mat[k][j])%MOD;
10    return c;
11}
12Mat operator ^ (Mat a,int b)
13{
14    Mat c;
15    c.clear();
16    for  ( int i = 0 ; i < 2 ; i++)
17	for ( int j = 0 ; j < 2 ; j++)
18	    c.mat[i][j]=(i==j); //初始化为单位矩阵。
19    while (b>0)
20    {
21	if (b&1) c = c * a;
22	b = b >> 1;
23	a = a * a;
24    }
25    return c;
26}
27int main()
28{
29	#ifndef  ONLINE_JUDGE 
30	freopen("code/in.txt","r",stdin);
31  #endif
 1	while (~scanf("%d",&n))
 2	{
 3	    if (n==-1) break;
 4	    if (n==0)
 5	    {
 6		printf("%d\n",0);
 7		continue;
 8	    }
 9	    M.mat[0][0] = 0;
10	    M.mat[0][1] = 1;
11	    M.mat[1][0] = 1;
12	    M.mat[1][1] = 1;
13	    M1.mat[0][0] = 0;
14	    M1.mat[1][0] = 1;
15	    Mat ans;
16	    ans.clear();
17	    ans = (M ^ n )* M1;
18	    printf("%d\n",ans.mat[0][0]);
19	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}