hdu 2680 Choose the best route
反向建图, 然后计算终点到各点的最短路径.
#include <stdio.h>
#include <queue>
using namespace std;
#define MAX 1001
#define INF 0xffffff
int map[MAX][MAX];
bool visited[MAX];
int lowcost[MAX];
int go[MAX];
int n, m, s, to;
/*
void spfa(int s) {
int i;
int now;
queue<int> Q;
for (i = 1; i <= n; i++) {
visited[i] = false;
lowcost[i] = INF;
}
lowcost[s] = 0;
visited[s] = true;
Q.push(s);
while (!Q.empty()) {
now = Q.front();
Q.pop();
for (i = 1; i <= n; i++) {
if (lowcost[now] + map[now][i] < lowcost[i]) {
lowcost[i] = lowcost[now] + map[now][i];
if (!visited[i]) {
visited[i] = true;
Q.push(i);
}
}
}
visited[now] = false;
}
}*/
void dijk(int s) {
int i, j;
int v, min;
for (i = 1; i <= n; i++) {
visited[i] = false;
lowcost[i] = map[s][i];
}
lowcost[s] = 0;
visited[s] = true;
for (i = 2; i <= n; i++) {
min = INF;
for (j = 1; j <= n; j++) {
if (!visited[j] && min > lowcost[j]) {
min = lowcost[j];
v = j;
}
}
if (min == INF) {
return ;
}
visited[v] = true;
for (j = 1; j <= n; j++) {
if (!visited[j] && min + map[v][j] < lowcost[j]) {
lowcost[j] = min + map[v][j];
}
}
}
}
int main() {
int i, j;
int a, b, c;
int ans;
while (scanf("%d%d%d", &n, &m, &to) == 3) {
ans = INF;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (i == j) {
map[i][j] = 0;
} else {
map[i][j] = INF;
}
}
}
for (i = 0; i < m; i++) {
scanf("%d%d%d", &a, &b, &c);
if (c < map[b][a]) {
map[b][a] = c;
}
}
scanf("%d", &s);
for (i = 0; i < s; i++) {
scanf("%d", &go[i]);
}
// spfa(to);
dijk(to);
for (i = 0; i < s; i++) {
if (ans > lowcost[go[i]]) {
ans = lowcost[go[i]];
}
}
if (ans == INF) {
printf("-1\n");
} else {
printf("%d\n", ans);
}
}
return 0;
}