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;
}

猜你喜欢

转载自blog.csdn.net/qq_31741481/article/details/84883846