zoukankan      html  css  js  c++  java
  • [Fibonacci] 矩阵快速幂

    Description

    请输出(Fib(n) mod 10000)
    (n leq 1000000000)

    Solution

    由于(n)的范围在(1e9)直接递推铁TLE,考虑矩阵快速幂
    Fibonacci数列有如下性质

    通过多次迭代

    算是个板子题吧,记得在WUST新生赛做过一道想矩阵快速幂的题,然而正解是找规律QAQ,在此贴个板子。

    Code

    #include <cstdio>
    #include <queue>
    #include <algorithm>
    #include <iostream>
    #include <queue>
    #include <cstring>
    #include <string>
    typedef long long LL;
    const int MOD = 1e4;
    using namespace std;
    
    struct Matrix{
    	LL m[2][2];
    	void print(){
    		for (int i = 0; i < 2; i++) {
    			for (int j = 0; j < 2; j++)
    				cout << m[i][j] << ' ';
    			cout << endl;	
    		}
    	
    	}
    } base, ans;
    
    Matrix times(Matrix a, Matrix b) {
    	Matrix ans;
    	ans.m[0][1] = ans.m[0][0] = ans.m[1][0] = ans.m[1][1] = 0;
    	for (int i = 0; i < 2; i++) {
    		for (int j = 0; j < 2; j++) {
    			for (int k = 0; k < 2; k++)
    				ans.m[i][j] = (ans.m[i][j] + a.m[i][k]*b.m[k][j])%MOD;
    		}
    	}
    	return ans;
    }
    
    void Matrixpow(LL x) {
    	base.m[0][0] = base.m[1][0] = base.m[0][1] = 1;
    	base.m[1][1] = 0;
    	ans.m[0][0] = ans.m[1][1] = 1;
    	ans.m[0][1] = ans.m[1][0] = 0;
    	while (x) {
    		if (x&1){
    			ans = times(ans, base);
    		} 
    		x >>= 1;
    		base = times(base, base);
    	}
    }
    LL N;
    int main(){
    	while (cin >> N) {
    		if (N == -1) break;
    		if (N == 0) {
    			cout << "0" << endl;
    			continue;
    		}
    		Matrixpow(N);
    		cout << ans.m[0][1] % MOD << endl; 
    	}	
    	return 0;
    }
    
  • 相关阅读:
    强迫症
    bzoj1758 [Wc2010]重建计划
    bzoj1070 [SCOI2007]修车
    bzoj3675 [Apio2014]序列分割
    bzoj1010 [HNOI2008]玩具装箱toy
    bzoj3697 采药人的路径
    bzoj2152 聪聪可可
    bzoj2599 [IOI2011]Race
    Ubuntu 18.04 LTS 下 GTK3 安装与编译
    启动或重启 dnsmasq 提示端口 53 被占用的解决方案
  • 原文地址:https://www.cnblogs.com/ez4zzw/p/12452083.html
Copyright © 2011-2022 走看看