题目链接:http://codeforces.com/problemset/problem/166/E
题意:给你一个四面体,从最上面那个顶点出发,走n步之后回到起点的方法有多少种。状态转移很简单dp[i][j] += dp[i-1][k](k != j); 但是n很大,这样做会超时,于是用矩阵快速幂来加速。A矩阵为0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <set> #include <queue> #include <map> #include <cmath> using namespace std; typedef long long LL; const int mod = 1e9+7; struct Matrix { LL a[4][4]; void clear() { memset(a, 0, sizeof(a)); } }A; Matrix multi(Matrix A, Matrix B) { Matrix C; C.clear(); for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) { for(int k = 0; k < 4; k++) C.a[i][j] = (C.a[i][j]+A.a[i][k]*B.a[k][j])%mod; } return C; } Matrix cal(int n) { if(n == 1) return A; Matrix ret = cal(n/2); ret = multi(ret, ret); if(n&1) ret = multi(ret, A); return ret; } int main() { int n; cin >> n; if(n == 1) { puts("0"); return 0; } A.clear(); for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) if(i != j) A.a[i][j] = 1; Matrix B = cal(n-1); int ans = 0; for(int i = 1; i < 4; i++) ans = (ans+B.a[i][0])%mod; cout << ans << endl; }
时间: 2024-12-27 23:48:10