给定一个 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;
}