快速幂
板子
const int mod = (int)1e4 + 7;
typedef vector<int> vec;
typedef vector<vec> mat;
// 矩阵乘法
mat operator*(mat &a, mat &b) {
mat c(a.size(), vec(b[0].size()));
for (int i = 0; i < a.size(); ++i) {
for (int j = 0; j < b.size(); ++j) {
for (int k = 0; k < b[0].size(); ++k) {
c[i][k] =
(c[i][k] + a[i][j] * b[j][k]) % mod;
}
}
}
return c;
}
//快速幂
mat pow(mat a, int n) {
mat b(a.size(), vec(a.size()));
for (int i = 0; i < a.size(); ++i) {
b[i][i] = 1;
}
while (n > 0) {
if (n & 1)
b = b * a;
a = a * a;
n >>= 1;
}
return b;
}
例题
POJ3734
-
思路
-
代码
// 为什么poj还不支持c++11
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define fast_io \
ios::sync_with_stdio(false); \
cin.tie(0)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int N = (int)1e5 + 5;
const int M = (int)1e5 + 5;
const double esp = 1e-8;
//------------------------------
const int mod = (int)1e4 + 7;
typedef vector<int> vec;
typedef vector<vec> mat;
mat operator*(mat &a, mat &b) {
mat c(a.size(), vec(b[0].size()));
for (int i = 0; i < a.size(); ++i) {
for (int j = 0; j < b.size(); ++j) {
for (int k = 0; k < b[0].size(); ++k) {
c[i][k] =
(c[i][k] + a[i][j] * b[j][k]) % mod;
}
}
}
return c;
}
mat pow(mat a, int n) {
mat b(a.size(), vec(a.size()));
for (int i = 0; i < a.size(); ++i) {
b[i][i] = 1;
}
while (n > 0) {
if (n & 1)
b = b * a;
a = a * a;
n >>= 1;
}
return b;
}
int main() {
fast_io;
int t, n;
cin >> t;
while (t--) {
cin >> n;
mat a(3, vec(3, 2));
a[0][1] = 1;
a[0][2] = 0;
a[2][0] = 0;
a[2][1] = 1;
// mat a = {{2, 1, 0}, {2, 2, 2}, {1, 1, 2}};
a = pow(a, n);
cout << a[0][0] << endl;
}
return 0;
}