HDU 2807 The Shortest Path 矩阵 + Floyd
水题, 直接模拟就可以。姿势要注意。。
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <stack> #include <map> #include <set> #include <climits> #include <iostream> #include <string> using namespace std; #define MP make_pair #define PB push_back typedef long long LL; typedef unsigned long long ULL; typedef vector<int> VI; typedef pair<int, int> PII; typedef pair<double, double> PDD; const int INF = INT_MAX / 3; const double eps = 1e-8; const LL LINF = 1e17; const double DINF = 1e60; const int maxn = 81; struct Matrix { int n, m, data[maxn][maxn]; Matrix(int n = 0, int m = 0): n(n), m(m) { memset(data, 0, sizeof(data)); } bool operator == (const Matrix &x) const { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(data[i][j] != x.data[i][j]) return false; } } return true; } void print() { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { printf("%d ", data[i][j]); } puts(""); } } }; Matrix operator * (Matrix &a, Matrix &b) { Matrix ret(a.n, b.m); for(int i = 1; i <= a.n; i++) { for(int j = 1; j <= b.m; j++) { for(int k = 1; k <= a.m; k++) { ret.data[i][j] += a.data[i][k] * b.data[k][j]; } } } return ret; } Matrix city[maxn]; int n, m, dist[maxn][maxn]; int main() { while(scanf("%d%d", &n, &m) != EOF) { if(n == 0 && m == 0) break; for(int i = 1; i <= n; i++) { city[i].n = city[i].m = m; for(int j = 1; j <= m; j++) { for(int k = 1; k <= m; k++) { scanf("%d", &city[i].data[j][k]); } } } memset(dist, 0, sizeof(dist)); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) dist[i][j] = INF; } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) if(i != j) { Matrix now = city[i] * city[j]; for(int k = 1; k <= n; k++) if(k != j && k != i) { if(now == city[k]) { dist[i][k] = 1; } } } } //floyd for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { for(int k = 1; k <= n; k++) { if(dist[j][i] + dist[i][k] < dist[j][k]) { dist[j][k] = dist[j][i] + dist[i][k]; } } } } int q; scanf("%d", &q); while(q--) { int x, y; scanf("%d%d", &x, &y); if(dist[x][y] < INF) printf("%d\n", dist[x][y]); else puts("Sorry"); } } return 0; }