1220. 统计元音字母序列的数目
矩阵快速幂
#include <iostream> #include<string.h> #include<stdio.h> using namespace std; class Solution { public: typedef long long ll; const ll mod = 1000000007; struct mat//定义矩阵结构体 { ll m[5][5]; mat() { memset(m, 0, sizeof(m)); } }; mat mul(mat &A, mat &B) { mat C; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { for (int k = 0; k < 5; k++) { C.m[i][j] = (C.m[i][j] + A.m[i][k] * B.m[k][j]) % mod; } } } return C; } mat pow(mat A, ll n) { mat B; for (int i = 0; i < 5; i++)//初始化方阵 B.m[i][i] = 0; //初始被乘矩阵的初值 B.m[0][0] = 1; B.m[1][0] = 1; B.m[2][0] = 1; B.m[3][0] = 1; B.m[4][0] = 1; while (n) { if (n & 1) B = mul(A, B);//注意这里,矩阵的左乘和右乘是不一样的,对应的系数矩阵也不一样 A = mul(A, A); n >>= 1; } return B; } int countVowelPermutation(int n) { mat A;//矩阵A是系数矩阵(转移矩阵) A.m[0][1] = 1; A.m[1][0] = 1, A.m[1][2] = 1; A.m[2][0] = 1, A.m[2][1] = 1, A.m[2][3] = 1, A.m[2][4] = 1; A.m[3][2] = 1, A.m[3][4] = 1; A.m[4][0] = 1; if (n == 1) { printf("5\n"); } // else if(n==2) // { // printf("45\n"); // } else { mat B = pow(A, n - 1); ll ans = B.m[0][0] + B.m[1][0] + B.m[2][0] + B.m[3][0] + B.m[4][0]; return ans % mod; } } }; int main() { Solution A; cout << A.countVowelPermutation(2) << endl; system("pause"); return 0; }
等风起的那一天,我已准备好一切