POJ 3268
题意: 各个点到x的最短距离 + x 到各个点的距离 的最大值
思路:跑两次dijkstra, 在找各个点到x的最短距离可以把g[a][b]反转为g[b][a]计算更方便。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
int g[N][N], dist[N], back[N];
int n, m, x;
bool st[N];
int dijkstra(){
//求出back的值
memset(back, 0x3f, sizeof back);
back[x] = 0;
for(int i = 1; i <= n; i ++){
int t = -1;
for(int j = 1; j <= n; j ++){
if(!st[j] && (t == -1 || back[t] > back[j])) t = j;
}
st[t] = true;
for(int j = 1; j <= n; j ++){
back[j] = min(back[j], back[t] + g[t][j]);
}
}
//去的
memset(st, 0 , sizeof st);
memset(dist, 0x3f, sizeof dist);
dist[x] = 0;
for(int i = 0; i < n; i ++){
int t = -1;
for(int j = 1; j <= n; j ++){
if(!st[j] && (t == -1 || dist[t] > dist[j])) t = j;
}
st[t] = true;
for(int j = 1; j <= n; j ++) dist[j] = min(dist[j], dist[t] + g[j][t]);
}
int ans = 1;
for(int i = 1; i <= n; i ++){
if(ans < back[i] + dist[i]) ans = dist[i] + back[i];
}
return ans;
}
int main(){
scanf("%d %d %d",&n,&m,&x);
int u, v, c;
memset(g, 0x3f, sizeof g);
while(m --){
scanf("%d %d %d",&u,&v,&c);
g[u][v] = c;
}
int t = dijkstra();
printf("%d\n",t);
return 0;
}