给定一个有向图,问从A点恰好走k步(允许重复经过边)到达B点的方案数mod p的值。
详见matrix67博客http://www.matrix67.com/blog/archives/276
#include <cstdio> #include <algorithm> #include <iostream> #include <string.h> typedef long long LL; using namespace std; const LL mod = 1000; LL n; struct Matrix { LL m[25][25]; }; Matrix Mul(Matrix a, Matrix b) { Matrix ans; for (LL i = 0; i < n; i++){ for (LL j = 0; j < n; j++){ ans.m[i][j] = 0; for (LL k = 0; k < n; k++){ ans.m[i][j] += a.m[i][k] * b.m[k][j]; ans.m[i][j] %= mod; } } } return ans; } Matrix quick(Matrix a, LL b) { Matrix ans; for (LL i = 0; i < n; i++) for (LL j = 0; j < n; j++) ans.m[i][j] = (i == j); while (b){ if (b & 1) ans = Mul(ans, a); a = Mul(a, a); b >>= 1; } return ans; } int main() { LL m; LL a, b, c, t; while (cin >> n >> m,n||m){ Matrix ans; for (LL i = 0; i < n;i++) for (LL j = 0; j < n; j++) ans.m[i][j] = 0; for (LL i = 0; i < m; i++){ cin >> a >> b; ans.m[a][b] = 1; } cin >> t; while (t--){ cin >> a >> b >> c; Matrix sum = quick(ans, c); cout << sum.m[a][b] << endl; } } return 0; }