zzuli 1524 最短路(队列优化dijkstra)

题目链接

本题不是讲迪杰斯特拉算法的,而是在该算法基础上用优先队列进行优化

首先回顾dijkstra,每次用一个已经更新过的点的最小值去更新周围的点,因此可以用一个优先队列(从小到大顺序)去保存这些已经更新过的,每次从队列里取队头的元素,判断这个位置的值更新过没有,没更新过就更新,更新过就继续找下一个,依次进行,知道队列空了,跳出循环

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int g[2510][2510];
int dist[2510];
int v[2510];
int n, m, a, b;
struct p{
	int index, dist;
	p(int index, int dist){
		this->index = index;
		this->dist = dist;
	}
	bool operator > (const p &a)const{
		return this->dist > a.dist;
	}
	bool operator < (const p &a)const{
		return this->dist < a.dist;
	}
};
int main()
{
	memset(g, 0x3f, sizeof g);
	memset(v, 0, sizeof v);
	memset(dist, 0x3f, sizeof dist);
	scanf("%d %d %d %d", &n, &m, &a, &b);
	priority_queue, greater

> q; for (int i = 1; i <= m; i++){ int x, y, z; scanf("%d %d %d", &x, &y, &z); g[x][y] = z; g[y][x] = z; } for (int i = 1; i <= n; i++){ if(g[a][i] != 0x3f3f3f3f){ dist[i] = g[a][i]; q.push(p(i, dist[i])); } } v[a] = 1; for(;;){ int ind, mn; p t(-1,-1); while(!q.empty() && v[q.top().index] == 1){ q.pop(); } if(!q.empty()){ t = q.top(); q.pop(); } ind = t.index; mn = t.dist; if(ind == -1)break; for (int i = 1; i <= n; i++){ if(dist[i] > mn + g[ind][i]){ dist[i] = mn + g[ind][i]; q.push(p(i, dist[i])); } } } printf("%d", dist[b]); return 0; }

 

你可能感兴趣的:(图论)