您的位置:首页 > 其它

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

2017-08-23 10:58 218 查看
  题意:(中问题,题意很简单

  思路: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 = 20;
const int N = 10;
const ll maxm = 1e7;
const int INF = 0x3f3f3f;
const int mod=1000;
const ll inf = 1e15 + 5;
const db eps = 1e-9;
int n, m;

struct Matrix{
int mat[maxn][maxn];
Matrix operator*(const Matrix& m)const{
Matrix tmp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
tmp.mat[i][j]=0;
for (int k = 0; 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 , 0 , sizeof(ans.mat));
for (int i=0; i<n; i++) {
ans.mat[i][i]=1;
}
while(k){
if(k&1)
ans = ans*m;
k >>= 1;
m = m*m;
}
return ans;
}

void solve() {
Matrix tmp;
while(scanf("%d%d", &n, &m)!=EOF) {
if (!n&&!m)  break;
memset(tmp.mat, 0, sizeof(tmp.mat));
for (int i=0; i<m; i++) {
int u, v;  scanf("%d%d", &u, &v);
tmp.mat[u][v]=1;
}
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 = 1;
//freopen("in.txt", "r", stdin);
// scanf("%d", &t);
while(t--)
solve();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: