Priority queue optimization dijkstra (for the first time all over again)

ahhhhhhhhhhh, bloggers have broken up, and most of the night without sleep is not a good thing Associate

 dijkstra seeking the shortest path each time you need to take the minimum current updated dist in, so you can use the top of a small heap, maintaining the value of the dist array, I get bored watching TV, try to write about, wa, change look, wa, then change, wa, nothing wrong ah, try again, WA , note the order should be maintained at a small value dist top of the heap, but also record what point is this, it is possible to use a structure.

I looked and looked, changed and changed, found me directly to the point into the priority queue, in accordance with the size of the point (1,2,,) placed, it is certainly on the GG.

I am going to open a special classification, record the code QAQ me silly in those days wrote

Attach the code (right):

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

 

Published 204 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43701790/article/details/104831693