矩阵快速幂模板
http://acm.hdu.edu.cn/showproblem.php?pid=5015
模板
const ll MOD = 998244353;
int add(int x, int y) { return x + y >= MOD ? x + y - MOD : x + y; }
int sub(int x, int y) { return x >= y ? x - y : x + MOD - y; }
struct mat{
ll m[2][2];
ll* operator[](int x) {
return m[x];
}
mat() { for (int i = 0;i < 2;i++) for (int j = 0;j < 2;j++) m[i][j] = 0; }
};
mat operator*(mat A, mat B){
mat C;
for (int i = 0;i < 2;i++){
for (int j = 0;j < 2;j++){
for (int k = 0;k < 2;k++) {
C[i][j] = add(C[i][j], A[i][k] * B[k][j] % MOD);
}
}
}
return C;
}
mat operator^(mat A, int p){
mat D;
D[0][0] = D[1][1] = 1;
while (p){
if (p & 1)D = D * A;A = A * A;p >>= 1;
}
return D;
}
经典例题
https://www.luogu.com.cn/problem/P3758
AC代码
const int MAXN = 31;
int n;
ll mod=2017;
bool len[31][31];
int main() {
int m;
cin>>n>>m;
memset(len,0,sizeof(len));
for(int i=1;i<=m;i++){
int u,v;
scanf("%d%d",&u,&v);
len[u][v]=1;
len[v][u]=1;
}
n++;
for(int i=0;i<n;i++) len[i][0]=1,len[i][i]=1; // 注:从0到0的一条边用于保存爆炸的方法数
Matrix s,f;
f[0][1]=1;
for(int i=0;i<n;i++)
for(int t=0;t<n;t++)
if(len[i][t]){
s[i][t]=1;
}
ll t;
cin>>t;
s=s^t;
f=f*s;
ll sum=0;
for(int i=0;i<n;i++) sum=(sum+f[0][i])%mod;
cout<<sum<<endl;
}