最短路径(dijkstra算法)

代码:《挑战程序设计竞赛》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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值