多对端点之间的最短路

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;
	}
}

完成!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值