单源最短路径---Dijkstra 算法--路径还原

本文介绍了一个使用Dijkstra算法寻找带权图中两点间最短路径的C++实现案例。通过读取文件输入顶点数量、边的数量及各边权重,算法能够找出从指定起点到任意其他节点的最短路径,并返回完整的路径列表。

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

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <fstream>
using namespace std;
const int maxn=100;
const int INF=999999;
int pre[maxn];
bool visited[maxn];
int d[maxn],cost[maxn][maxn],n,m; //n vertexs,1,2,...n. m edges.
void dijkstra(int s)
{
	memset(pre,-1,sizeof(pre));
	fill(d+1,d+1+n,INF);
	memset(visited,0,sizeof(visited));
	d[s]=0;
	while(1)
	{
		int index=-1;
		for(int u=1;u<=n;u++){
			if(!visited[u] && (index==-1|| d[u]<d[index]))
				index=u;
		}
		if(index==-1)break;
		visited[index]=1;
		for(int u=1;u<=n;u++){
			if( d[u]>d[index]+cost[index][u])
			{
				d[u]=d[index]+cost[index][u];
				pre[u]=index;
			}	
		}
	}
}
vector<int> get_path(int t)
{
	vector<int> path;
	path.clear();
	for(;t!=-1;t=pre[t])
	{
		path.push_back(t);
	}
	reverse(path.begin(),path.end());
	return path;
} 
int main()
{
	ifstream fin;
	fin.open("input.txt");
	cout<<fin.is_open()<<endl;
	while(fin>>n>>m)
	{
		
		for(int i=1;i<=n;i++)       //这里一定要进行预处理 
			for(int j=1;j<=n;j++){
				if(i==j)cost[i][j]=0;
				else cost[i][j]=INF;
			}
		for(int i=1;i<=m;i++)
		{
			int u,v,c;
			fin>>u>>v>>c;
			cost[u][v]=c; //DAG
		}
		int s,t;
		fin>>s>>t;
		dijkstra(s);
		cout<<"the shortest path from "<<s<<" to "<<t<<" is: "<<d[t]<<endl;
		cout<<"the path is :"<<endl;
		vector<int> path=get_path(t); //得到最短路径 
		for(int i=0;i!=path.size();i++)cout<<path[i]<<" ";
		cout<<endl;
	}
}

给出一组测试:

5
7
1 2 10
1 4 30
1 5 100
2 3 50
3 5 10
4 3 20
4 5 60

1 5

输出结果:

1

the shortest path from 1 to 5 is :60

the path is :

1 4 3 5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值