(poj3159)dijkstra优先队列实现

poj3159

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std; 
int n,m,head[30010];
int c;
struct is{
	int index,cost;
	friend bool operator <(is a,is b){
		
		if(a.cost== b.cost)return a.index < b.index;
		return a.cost > b.cost; 
	}
	
}dis;//?????????????
struct node{
	int v,w,next;
}edge[150010];

void add(int u, int v,int w){
	edge[c].v = v;
	edge[c].w = w;
	edge[c].next = head[u];
	head[u] = c++;
}

int dijkstra(){
	priority_queue<is>q;
	dis.index= 1;
	dis.cost = 0;
	q.push(dis);
	int vis[30010];
	memset(vis,0,sizeof(vis));
	while(!q.empty()){
		dis = q.top();
		q.pop();
		int v = dis.index;
		int cost = dis.cost;
		//printf("---%d\n",cost);
		if(v == n)return cost;
		vis[v] = 1;
		for(int i = head[v];i!= -1;i = edge[i].next){
			int vv = edge[i].v;
			dis.index = vv;
			dis.cost = cost + edge[i].w;
			if(vis[vv] == 0)
				q.push(dis);
			
			
		}
	}
	
}

int main(){

	scanf("%d%d",&n,&m);
	c = 0;
	for(int i =1 ;i<= n;i++)head[i] = -1;
	for(int i = 0;i<m;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		add(u,v,w);
	}
	printf("%d\n",dijkstra());
}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/yuanhanchun/article/details/48182549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞