flyod求最短路

给定一个 nn 个点 mm 条边的有向图,图中可能存在重边和自环,边权可能为负数。

再给定 kk 个询问,每个询问包含两个整数 xx 和 yy,表示查询从点 xx 到点 yy 的最短距离,如果路径不存在,则输出 impossible

数据保证图中不存在负权回路。

输入格式

第一行包含三个整数 n,m,kn,m,k。

接下来 mm 行,每行包含三个整数 x,y,zx,y,z,表示存在一条从点 xx 到点 yy 的有向边,边长为 zz。

接下来 kk 行,每行包含两个整数 x,yx,y,表示询问点 xx 到点 yy 的最短距离。

输出格式

共 kk 行,每行输出一个整数,表示询问的结果,若询问两点间不存在路径,则输出 impossible

数据范围

1≤n≤2001≤n≤200,
1≤k≤n21≤k≤n2
1≤m≤200001≤m≤20000,
图中涉及边长绝对值均不超过 1000010000。

输入样例:

3 3 2
1 2 1
2 3 2
1 3 1
2 1
1 3

输出样例:

impossible
1

运用了动态规划的思想,很巧妙!!


#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

inline int read() {
	char c = getchar();
	int res = 0, flag = 1;
	while (!isdigit(c)) {
		if (c == '-') 
			flag = -1;
		c = getchar();
	}

	while (isdigit(c)) {
		res = (res << 1) + (res << 3) + (c ^ 48);
		c = getchar();
	}

	return res * flag;
}

const int N = 1010, INF = 1e09;
int g[N][N];
int n, m;
void flyod() {
	for (int k = 1; k <= n; k ++) {
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
			}
		}
	}
}

int main() {
	int k;
	n = read();
	m = read();
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (i == j) g[i][j] = 0;
			else g[i][j] = INF;
		}
	}

	k = read();
	while (m --) {
		int a, b, c;
		a = read();
		b = read();
		c = read();
		g[a][b] = min(g[a][b], c);
	}

	flyod();

	while (k --) {
		int x, y;
		x = read();
		y = read();
		if (g[x][y] > 0x3f / 2) cout << "impossible" << endl;
		cout << g[x][y] << endl;
	}

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值