代码:《挑战程序设计竞赛》2.5.4
1.邻接矩阵
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX_N 100
#define INF 1000
int cost[MAX_N][MAX_N]; //cost[u][v]即u到v所用的权值
bool used[MAX_N]; //判断点是否用过
int V, E; //顶点和边的数目
int d[MAX_N]; //距离
void Findshortestpath(int s)
{
fill(d, d + V, INF); //初始化
fill(used, used + V, false); //初始化
d[s] = 0;
while (true)
{
int v = -1; //记录未使用的顶点中距离最小的顶点
//从未使用的顶点中选择距离最小的一个顶点
for (int u = 0; u < V; u++)
{
if (used[u] == false && (v == -1 || d[u] < d[v])) v = u; /*顶点u没用过且为第一个搜索
的点或者点u的距离小于当前距离最小点*/
}
if (v == -1) break; //如果无法更新,则中断
used[v] = true;
for (int u = 0; u < V; u++)
{
d[u] = min(d[u], cost[v][u]); //从当前距离最短点出发,把所有顶点的最短距离更新
}
}
}
int main()
{
//初始化图
//输入起点终点,并调用函数计算出最短距离
return 0;
}
2.STL的priority_queue实现
#include<iostream>
#include<queue>
using namespace std;
#define MAX_N 100
#define INF 1000
class edge //边
{
public:
int to, cost;
};
typedef pair<int, int> P; //first是最短距离, second是编号
int V, E; //顶点数目、边的数目
vector<edge> G[MAX_N]; //图
int d[MAX_N]; //最短距离
void FindShortestPath(int s)
{
priority_queue<P, vector<P>, greater<P> > que;
fill(d, d + V, INF);
d[s] = 0;
que.push(P(0, s));
while (!que.size())
{
P p = que.top;
que.pop();
int v = p.second;
if (d[v] < p.first) continue;
for (int i = 0; i < G[v].size(); i++)
{
edge e = G[v][i];
if (d[e.to] > d[v] + e.cost)
{
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
int main()
{
//初始化图
//输入起点终点,并调用函数计算出最短距离
return 0;
}