本题思路:对原图和原图的逆图分别用一次最短路,找出最大值即可。
一开始是我是对每个顶点spfa搜了一波,结果判题时间巨长,还好这个题的数据量不是很大,所以就用了另一种思路。
参考代码:spfa单结点爆搜版
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std; const int maxn = + , INF = 0x3f3f3f3f;
struct edge {
int to, cost;
};
int n, m, x, ans, dist[maxn];
vector<edge> G[maxn];
bool vis[maxn]; void addedge(int u, int v, int w) {
G[u].push_back({v, w});
} int spfa(int source, int aid) {
memset(vis, false, sizeof vis);
for(int i = ; i <= n; i ++)
dist[i] = (i == source ? : INF);
queue <int> Q;
Q.push(source);
vis[source] = true;
while(!Q.empty()) {
int now = Q.front();
Q.pop();
for(int i = ; i < G[now].size(); i ++) {
edge e = G[now][i];
if(dist[e.to] > dist[now] + e.cost) {
dist[e.to] = dist[now] + e.cost;
if(!vis[e.to]) Q.push(e.to);
}
}
}
return dist[aid];
} int main () {
ans = ;
int u, v, w;
cin >> n >> m >> x;
for(int i = ; i <= m; i ++) {
cin >> u >> v >> w;
addedge(u, v, w);
}
for(int i = ; i <= n; i ++)
ans = max(spfa(i, x) + spfa(x, i), ans);
cout << ans << endl;
return ;
}
对原图和逆图分别进行一次Dijkstra的终极版本
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std; const int maxn = + , INF = 0x3f3f3f3f;
struct edge {
int to, cost;
};
int n, m, x, k, ans, dist1[maxn], dist2[maxn], G[maxn][maxn];;
bool vis[maxn]; void Dijkstra(int lowcost[]) {
for(int i = ; i <= n; i ++)
lowcost[i] = INF;
lowcost[x] = ;
memset(vis, false, sizeof vis);
for(int i = ; i <= n; i ++) {
int minf = INF;
for(int j = ; j <= n; j ++)
if(minf > lowcost[j] && !vis[j]) {
k = j;
minf = lowcost[j];
}
vis[k] = true;
for(int j = ; j <= n; j ++)
if(!vis[j] && lowcost[j] > lowcost[k] + G[k][j])
lowcost[j] = lowcost[k] + G[k][j];
}
} int main () {
ans = ;
int u, v, w;
cin >> n >> m >> x;
for(int i = ; i <= n; i ++)
for(int j = ; j <= n; j ++)
if(i == j) G[i][j] = ;
else G[i][j] = INF;
for(int i = ; i <= m; i ++) {
cin >> u >> v >> w;
G[u][v] = min(G[u][v], w);
}
Dijkstra(dist1);
for(int i = ; i <= n; i ++)
for(int j = ; j < i; j ++)
if(G[i][j]) swap(G[i][j], G[j][i]);
Dijkstra(dist2);
for(int i = ; i <= n; i ++)
ans = max(ans, dist1[i] + dist2[i]);
cout << ans << endl;
return ;
}