UVA - 10229 - Modular Fibonacci (矩陣快速冪 + fibonacci)

來源:互聯網
上載者:User

標籤:acm   uva   fibonacci   矩陣快速冪   


題目傳送:UVA - 10229


思路:就是簡單的矩陣快速冪求fibonacci數列,然後注意可能中間結果會爆int,因為2^19有50多萬


AC代碼:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <cmath>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#include <deque>#include <cctype>#define LL long long#define INF 0x7fffffffusing namespace std;int mp[20];LL n, m;void init() {mp[0] = 1;for(int i = 1; i < 20; i ++) {mp[i] = 2 * mp[i - 1];}}struct matrix {LL m[2][2];};matrix ans;matrix base = {1, 1, 1, 0};matrix multiply(matrix a, matrix b, LL MOD) {matrix ret;for(int i = 0; i < 2; i ++) {for(int j = 0; j < 2; j ++) {ret.m[i][j] = 0;for(int k = 0; k < 2; k ++) {ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;}}}return ret;}LL kmod(matrix a, LL n, LL MOD) {matrix ans = {1, 0, 0, 1};while(n) {if(n & 1) ans = multiply(ans, a, MOD);a = multiply(a, a, MOD);n >>= 1;}return ans.m[0][1];}int main() {init();while(cin >> n >> m) {cout << kmod(base, n, mp[m]) << endl;}return 0;}














UVA - 10229 - Modular Fibonacci (矩陣快速冪 + fibonacci)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.