poj 2387 最短路径Dijkstra

本文介绍了一种使用C++实现的Dijkstra算法,用于解决单源最短路径问题。通过构建邻接矩阵和优先队列,算法能够高效地找到从起点到所有其他节点的最短路径。

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

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
#define INF 0x3fffffff
#define NUM 1005
#define NUM2 2005
struct Edge{
	int to;
	int cost;
}edge;
vector<Edge> edges[NUM];
int visited[NUM];
int dist[NUM];
void init(){
	for(int i=0;i<NUM;i++){
		visited[i]=0;
		dist[i]=INF;
	}
}
int main(){
	int N,T;
	scanf("%d %d",&T,&N);
	for(int i=0;i<T;i++){
		int from,to,cost;
		scanf("%d %d %d",&from,&to,&cost);
		struct Edge tmp;
		tmp.to=to;
		tmp.cost=cost;
		edges[from].push_back(tmp);
		tmp.to=from;
		tmp.cost=cost;
		edges[to].push_back(tmp);
	}
	init();
	queue<int> q;
	q.push(N);
	dist[N]=0;
	while(!q.empty()){
		int from=q.front();
		q.pop();
		for(int j=0;j<edges[from].size();j++){
			int to=edges[from][j].to;
			int cost=edges[from][j].cost;
			if(visited[to]==0){
				if(dist[to]>dist[from]+cost){
					dist[to]=dist[from]+cost;
					q.push(to);
				}
			}
		}
	}
	cout<<dist[1]<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值