D - Silver Cow Party POJ - 3268
dijkstra 是 O(n2),堆优化一下, O(nlogn)
对每个点跑一次 dj, 取 max(dis(x->i)+dis(i->x))
总复杂度 O(n2logn) = 1e7
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
#define inf 0x3f3f3f3f
using namespace std;
typedef pair<int,int> PII;
const int maxn = 101000;
int dis[maxn], dist[maxn];
bool vis[maxn];
int head[maxn], cnt;
struct node{
int to, next, w;
}e[maxn];
void add(int u, int v, int w) {
e[++cnt].next = head[u];
e[cnt].to = v;
e[cnt].w = w;
head[u] =cnt;
}
void dijkstra(int sta, int d[]) {
memset(vis, 0, sizeof(vis));
d[sta] = 0;
priority_queue<PII, vector<PII>, greater<PII> > heap;
heap.push({0, sta});
while(heap.size()) {
PII now = heap.top(); heap.pop();
int u = now.second; int len = now.first;
if(vis[u]) continue;
vis[u] = 1;
for(int i = head[u]; i; i = e[i].next) {
int to = e[i].to;
if(d[to] > len + e[i].w) {
d[to] = len + e[i].w;
heap.push({d[to], to});
}
}
}
}
int main() {
// freopen("test.in", "r", stdin);
memset(dist, inf, sizeof(dist));
int N, M, X, ans = -1;
scanf("%d%d%d", &N, &M, &X);
for(int i = 1; i <= M; i++) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
dijkstra(X, dist);
for(int i = 1; i <= N; i++) {
memset(dis, inf, sizeof(dis));
if(i == X) continue;
dijkstra(i, dis);
ans = max(ans, dis[X] + dist[i]);
}
printf("%d\n", ans);
return 0;
}