hdu 2157 How many ways?? 矩阵快速幂
题目链接:
hdu 2157 How many ways??
分析:令M[i][j] = 1 表示从i到j 连通,即i, j经过一个点到达的方案数为1。 那么∑(M[i][k] + M[k][j]), k∈(0, N-1), 就表示i, j经过两个点到达的方案数。即将矩阵M^n就可以求出i, j经过N个点到达的方案数。
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
typedef __int64 LL;
// typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 20;
const int MOD = 1000;
int T;
int K, A, B, N, M;
int s, t;
struct Mat {
LL mat[MAXN][MAXN];
Mat() {
memset(mat, 0, sizeof(mat));
}
Mat(LL arr[][MAXN]) {
Mat();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
mat[i][j] = arr[i][j];
}
}
}
} E, tmat, imat, res;
void init() {
E = Mat();
for (int i = 0; i < N; i++) {
E.mat[i][i] = 1;
}
}
Mat mat_mul(const Mat& a, const Mat& b, const int& MOD) {
Mat ret = Mat();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
ret.mat[i][j] = 0;
for (int k = 0; k < N; k++) {
ret.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
ret.mat[i][j] %= MOD;
}
}
}
return ret;
}
Mat mat_power(const Mat& m, int y, const int& MOD) {
Mat x = m, ret = E;
while (y) {
if (y & 1) ret = mat_mul(ret, x, MOD);
x = mat_mul(x, x, MOD);
y >>= 1;
}
return ret;
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while (~scanf("%d %d", &N, &M) && N) {
init();
tmat = Mat();
while (M --) {
scanf("%d %d", &s, &t);
tmat.mat[s][t] = 1;
}
scanf("%d", &T);
while (T --) {
scanf("%d %d %d", &A, &B, &K);
res = mat_power(tmat, K, MOD);
printf("%d\n", res.mat[A][B]);
}
}
return 0;
}