测试数据:
8 15
4 5 0.35
5 4 0.35
4 7 0.37
5 7 0.28
7 5 0.28
5 1 0.32
0 4 0.38
0 2 0.26
7 3 0.39
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93
测试结果:
1 1.05
2 0.26
3 0.99
4 0.38
5 0.73
6 1.51
7 0.60
PS:边的权重必须非负。
PS2:就算有平行边和自环也请方向使用。
代码:
#include<cstdio> #include<cstring> #include<vector> #include<queue> #include<utility> #include<functional> using namespace std; const int mx = 10005; typedef pair<double, int> P; ///first是最短距离,second是顶点编号 struct edge { double cost; int to; void read() { scanf("%d%lf", &to, &cost); } } e; vector<edge> G[mx]; double disTo[mx]; priority_queue<P, vector<P>, greater<P> > pq; /* 使用:dj(起点) 输出:disTo[目标点] 复杂度:平均情况:O(ElogV),最坏情况:O(ElogV) */ void dj(int s) { P p; int v, i; memset(disTo, 100, sizeof(disTo)); disTo[s] = 0.0; while (!pq.empty()) pq.pop(); pq.push(P(0.0, s)); while (!pq.empty()) { p = pq.top(), pq.pop(); v = p.second; ///v视作e.from if (p.first > disTo[v]) continue; for (i = 0; i < G[v].size(); ++i) { e = G[v][i]; if (disTo[e.to] > disTo[v] + e.cost) ///v视作e.from { disTo[e.to] = disTo[v] + e.cost; pq.push(P(disTo[e.to], e.to)); } } } } int main() { int n, m, i, a; while (~scanf("%d%d", &n, &m)) { for (i = 0; i < n; ++i) G[i].clear(); while (m--) { scanf("%d", &a); e.read(); G[a].push_back(e); } dj(0); for (i = 1; i < n; ++i) printf("%d %.2f\n", i, disTo[i]); putchar(10); } return 0; }
PS:O(V^2)复杂度的算法见http://blog.csdn.net/synapse7/article/details/18253329
PS2:对于有向无环图,有更简单且更快的算法,见http://blog.csdn.net/synapse7/article/details/19284933
另:若有负权重边,须使用Bellman-Ford算法(基于队列),但这一算法的局限性又在于图中不能存在负权重环
复杂度:平均情况:O(E+V),最坏情况:O(EV)