POJ 3268 Silver Cow Party 最短路径 Dijkstra算法优化

堆优化的Dijkstra算法确实非常快,求解最短路径比BellmanFord算法和Floyd算法快了太多。

#include 
#include 
#include 
using namespace std;
typedef pair P;
vector

edges[1007]; int d[1007], inf = 1000000000, N, M, X, fromEnd[1007]; bool used[1007]; void input() { scanf("%d%d%d", &N, &M, &X); int from, to, cost; for (int i = 1; i <= M; i++) { scanf("%d%d%d", &from, &to, &cost); edges[from].push_back(P(cost, to)); } } void dijkstra(int s) { for (int i = 1; i <= N; i++) { d[i] = inf; used[i] = false; } d[s] = 0; priority_queue, greater

> que; que.push(P(0, s)); while (!que.empty()) { P current = que.top(); que.pop(); if (used[current.second] || current.first > d[current.second]) { continue; } used[current.second] = true; for (int i = 0; i < edges[current.second].size(); i++) { P toEdge = edges[current.second][i]; if (!used[toEdge.second] && d[current.second] + toEdge.first < d[toEdge.second]) { d[toEdge.second] = d[current.second] + toEdge.first; que.push(P(d[toEdge.second], toEdge.second)); } } } } void solve() { dijkstra(X); for (int i = 1; i <= N; i++) { fromEnd[i] = d[i]; } int ans = 0; for (int i = 1; i <= N; i++) { if (i == X) { continue; } dijkstra(i); if (fromEnd[i] + d[X] > ans) { ans = fromEnd[i] + d[X]; } } printf("%d\n", ans); } int main() { input(); solve(); return 0; }

你可能感兴趣的:(算法,数据结构,图论)