题目链接:http://lightoj.com/volume_showproblem.php?problem=1002
Time Limit: 3 second(s) Memory Limit: 32 MB
Problem Description
I am going to my home. There are many cities and many bi-directional roads between them. The cities are numbered from 0 to n-1 and each road has a cost. There are m roads. You are given the number of my city t where I belong. Now from each city you have to find the minimum cost to go to my city. The cost is defined by the cost of the maximum road you have used to go to my city.
For example, in the above picture, if we want to go from 0 to 4, then we can choos
- 0 - 1 - 4 which costs 8, as 8 (1 - 4) is the maximum road we used
- 0 - 2 - 4 which costs 9, as 9 (0 - 2) is the maximum road we used
- 0 - 3 - 4 which costs 7, as 7 (3 - 4) is the maximum road we used
So, our result is 7, as we can use 0 - 3 - 4.
Input
Input starts with an integer T (≤ 20), denoting the number of test cases.
Each case starts with a blank line and two integers n (1 ≤ n ≤ 500) and m (0 ≤ m ≤ 16000). The next m lines, each will contain three integers u, v, w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 20000) indicating that there is a road between u and v with cost w. Then there will be a single integer t (0 ≤ t < n). There can be multiple roads between two cities.
Output
For each case, print the case number first. Then for all the cities (from 0 to n-1) you have to print the cost. If there is no such path, print 'Impossible'.
Sample Input
2
5 6
0 1 5
0 1 4
2 1 3
3 0 7
3 4 6
3 1 8
15 4
0 1 5
0 1 4
2 1 3
3 4 7
1
Output for Sample Input
Case 1:
4
0
3
7
7
Case 2:
4
0
3
Impossible
Impossible
Note
Dataset is huge, user faster I/O methods.
Problem solving report:
Description: 计算所有的城市到T城市的最小花费中其中的最大距离。
Problem solving: 最短路的变形题,改一下松弛条件就行了。
Accepted Code:
/*
* @Author: lzyws739307453
* @Language: C++
*/
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 505;
const int MAXM = 16005;
const int inf = 0x3f3f3f3f;
struct edge {
int u, v, w;
edge() {}
edge(int u, int v, int w) : u(u), v(v), w(w) {}
}e[MAXM << 1];
bool vis[MAXN];
int cnt, f[MAXN], dis[MAXN];
void Add_edge(int u, int v, int w) {
e[++cnt] = edge(f[u], v, w);
f[u] = cnt;
}
void init() {
cnt = 0;
memset(f, -1, sizeof(f));
memset(vis, 0, sizeof(vis));
memset(dis, 0x3f, sizeof(dis));
}
void Spfa(int s) {
queue <int> Q;
Q.push(s);
dis[s] = 0;
vis[s] = true;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
vis[u] = false;
for (int i = f[u]; ~i; i = e[i].u) {
int v = e[i].v;
if (dis[v] > max(dis[u], e[i].w)) {
dis[v] = max(dis[u], e[i].w);
if (!vis[v]) {
Q.push(v);
vis[v] = true;
}
}
}
}
}
int main() {
int kase = 0;
int t, n, m, u, v, w;
scanf("%d", &t);
while (t--) {
init();
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &u, &v, &w);
Add_edge(u, v, w);
Add_edge(v, u, w);
}
scanf("%d", &u);
Spfa(u);
printf("Case %d:\n", ++kase);
for (int i = 0; i < n; i++) {
if (dis[i] < inf)
printf("%d\n", dis[i]);
else printf("Impossible\n");
}
}
return 0;
}