优先队列优化 dijkstra (第一次重新来过)

ahhhhhhhhhhh,博主已经裂开了,大半夜不睡觉准没好事

 dijkstra求最短路每次需要取当前更新过的dist中的最小值,因此可以用一个小顶堆,维护这个dist数组中的值,我看着电视剧觉得无聊,就试试写一下,wa,改一下,wa,再改,wa,没毛病啊,再试试,wa,注意维护的顺序应该是dist值小的在堆顶,同时还要记录这是哪个点,所以可以用一个结构体。

我看了又看,改了又改,发现,我直接把点放到优先队列里了,是按照点的大小(1,2,,,)摆放的,那肯定就GG了。

我准备专门开一个分类,记录我那些犯傻的日子里写下的代码QAQ

附上代码(正确的):

/**
 * Author : correct
 */
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#define mem(a, b) memset(a, b, sizeof a)
using namespace std;
const int M = 6210 * 2, N = 2520;
int head[M], nex[M], to[M], cnt, ed[M];
void add(int a, int b, int c){
	to[++cnt] = b;
	nex[cnt] = head[a];
	head[a] = cnt;
	ed[cnt] = c;
}
int n, m, s, t;
int dist[N];
bool vis[N];
struct p{
	int x, dist;
	bool operator < (const p& a)const{
		return this->dist < a.dist;
	}
	bool operator > (const p& b)const{
		return this->dist > b.dist;
	}
	p(){

	}
	p(int x, int dist){
		this->x = x;
		this->dist = dist;
	}
};
priority_queue<p, vector<p>, greater<p> > q;
int main()
{
	mem(head, -1);
	mem(nex, -1);
	cnt = 0;
	mem(dist, 0x3f);
	mem(vis, 0);
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m >> s >> t;
	dist[s] = 0;
	q.push(p(s, 0));
	while (m--){
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
		add(b, a, c);
	}
	while (q.size()){
		p T = q.top();
		int ind = T.x;
		q.pop();
		if (vis[ind]){
			continue;
		}
		vis[ind] = 1;
		for (int i = head[ind]; ~i; i = nex[i]){
			int y = to[i];
			int c = ed[i];
			if (dist[y] > dist[ind] + c){
				dist[y] = dist[ind] + c;
				q.push(p(y, dist[y]));
			}
		}
	}
	cout << dist[t];
	return 0;
}
发布了204 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43701790/article/details/104831693