Dijsktra算法

#include<iostream>
#include<vector>
#include<queue>
#define LL long long
#define INF 99999999
#define maxn 1005
using namespace std;
int n, m, startv, endv;//点、边、起点,终点 
struct Node
{
	int pos, c;
	bool operator <(const Node &p)const//运算符重载 
	{
		return c > p.c;
	}
};
vector<Node>g[maxn];//邻接表 
int dis[maxn];//距离数组 
void init()//初始化 
{
	for (int i = 1; i <= n; i++)
		g[i].clear();
}
void dij(int from)//输入起点 
{
	priority_queue<Node>q;//优先队列 
	for (int i = 0; i <= n; i++)
		dis[i] = INF;
	dis[from] = 0;
	Node now = { from,0 };
	q.push(now);
	while (!q.empty())
	{
		now = q.top();
		q.pop();
		int v = now.pos;
		if (dis[v] < now.c)//如果到同一点的距离有多组,取最小的 
			continue;
		for (int i = 0; i < g[v].size(); i++)
		{
			Node e;
			e = g[v][i];
			if (dis[e.pos] > dis[v] + e.c)
			{
				dis[e.pos] = dis[v] + e.c;
				Node next = { e.pos,dis[e.pos] };
				q.push(next);
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	init();
	for (int i = 0; i < m; i++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		Node p;
		p.pos = b;
		p.c = c;
		g[a].push_back(p);
		p.pos = a;
		g[b].push_back(p);
	}
	cin >> startv >> endv;
	dij(startv);
	cout << dis[endv] << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值