经典矩阵快速幂之二-----hdu2157(走k步到

时间:2024-11-15 17:07:37

  题意:(中问题,题意很简单

  思路:a走k步到b,其实就是A^k,ans.mat[a][b]就是答案。

  其实就是离散的邻接矩阵那个P(不想证明,逃

#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<cstring>
#include<queue>
#include<set>
#include<string>
#include<map>
#include <time.h>
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef double db;
const int maxn = ;
const int N = ;
const ll maxm = 1e7;
const int INF = 0x3f3f3f;
const int mod=;
const ll inf = 1e15 + ;
const db eps = 1e-;
int n, m; struct Matrix{
int mat[maxn][maxn];
Matrix operator*(const Matrix& m)const{
Matrix tmp;
for (int i = ; i < n; i++) {
for (int j = ; j < n; j++) {
tmp.mat[i][j]=;
for (int k = ; k < n; k++) {
tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%mod;
tmp.mat[i][j]+=mod;
tmp.mat[i][j] %= mod;
}
}
}
return tmp;
}
}; Matrix Pow(Matrix m, int k) {
Matrix ans;
memset(ans.mat , , sizeof(ans.mat));
for (int i=; i<n; i++) {
ans.mat[i][i]=;
}
while(k){
if(k&)
ans = ans*m;
k >>= ;
m = m*m;
}
return ans;
} void solve() {
Matrix tmp;
while(scanf("%d%d", &n, &m)!=EOF) {
if (!n&&!m) break;
memset(tmp.mat, , sizeof(tmp.mat));
for (int i=; i<m; i++) {
int u, v; scanf("%d%d", &u, &v);
tmp.mat[u][v]=;
}
int t; scanf("%d", &t);
while(t--) {
Matrix hh;
int a, b, k; scanf("%d%d%d", &a, &b, &k);
hh=Pow(tmp, k);
printf("%d\n", hh.mat[a][b]);
}
} }
int main() {
int t = ;
//freopen("in.txt", "r", stdin);
// scanf("%d", &t);
while(t--)
solve();
return ;
}