(poj3159)dijkstra优先队列实现

本文详细解析了POJ 3159题目的Dijkstra算法实现过程,介绍了如何通过优先级队列来寻找最短路径,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值