Description
N cities named with numbers 1 … N are connected with one-way roads. For each pair of cities i and j, you need to find the shortest path from city i to city j.
Input
The first line contains three integers N, K and Q (2<=N<=100, 1<=K<=10000, 1<=Q<=10000). N is the number of cities, K is the number of roads, and Q is the number of queries. Each of following K lines contains three integers i, j, d (1<=i,j<=N, 0<d<10000), indicates there is a road from city i to city j, and its length is d. The next Q lines describes the queries, each line contains two integers i and j (1<=i,j<=N).
Output
For each query, you need to print the shortest path in one line. If there is no path between the query cities pair, you should print “-1”.
Sample Input
4 3 2
1 2 3
2 3 4
2 4 3
1 3
2 4
Sample Output
7
3
分析
这道题主要是求多对端点之间的最短路,所以用Floyd-Warshall算法。
代码
#include <iostream>
using namespace std;
const int MAXN = 101;
//const int MAXK = 10001;
//const int MAXQ = 10001;
int dist[MAXN][MAXN];
void init() {
for (int i = 0; i < MAXN; i++) {
for (int j = 0; j < MAXN; j++) {
dist[i][j] = -1;
}
}
}
int main() {
//初始化
init();
int N, K, Q;
cin >> N >> K >> Q;
for (int i = 0; i < N; i++) {
dist[i][i] = 0;
}
for (int i = 0; i < K; i++) {
int b, d, s;
cin >> b >> d >> s;
if (dist[b - 1][d - 1] == -1 or dist[b - 1][d - 1] > s)
dist[b - 1][d - 1] = s;
}
//Floyd-Warshall算法
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if ((dist[i][k] != -1 and dist[k][j] != -1) and(dist[i][j] == -1 or dist[i][j] > dist[i][k] + dist[k][j])) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
//输出
for (int i = 0; i < Q; i++) {
int b, d;
cin >> b >> d;
cout << dist[b - 1][d - 1] << endl;
}
}
完成!