单源最短路问题——Dijkstra算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/88555075

 共有n个顶点,m条边,其中s为初始点,求从s到各点的最短距离

样例输入:

7 10 0

0 1 2

0 6 5

1 6 4

1 5 6

1 2 10

2 3 5

2 4 3

3 4 9

4 5 1

5 6 2

样例输出:

0 2 11 16 8 7 5

详细代码: 

#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int cost[1000][1000]; //表示每一个顶点到其他顶点的边长 
int d[1000]={0};    // 代表从顶点到各点的最短距离 
int v,m,s;           //代表有v个顶点 m个边 s表示出发点 
bool used[1000];//标记是否已经使用过 
void dijkstra(int s1){
	while(true){
		int f = -1;
		for(int i=0;i<v;i++){
			if(!used[i] && (f == -1 || d[f]>d[i]))f=i;//找到一个距离初始点较近且没被使用过的顶点 
		}
		if(f == -1)break;
		used[f] = true;
		for(int i=0;i<v;i++){
			d[i]=min(d[i],d[f]+cost[f][i]);//更新d数组 
		} 
	}
}
int main()
{
	cin>>v>>m>>s;
	for(int i=0;i<v;i++){
		for(int j=0;j<v;j++){
			cost[i][j]=999999;
		}
	}//初始化cost数组 
	fill(d,d+v,999999);
	fill(used,used+v,false);
	d[s]=0;
	for(int i=0;i<m;i++){
		int x,y,z;//代表从x到y的边长为z 
		cin>>x>>y>>z;
		cost[x][y]=z;
		cost[y][x]=z; 
	} 
	dijkstra(s);
	for(int i=0;i<v;i++){
		cout<<d[i]<<" ";
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/88555075
今日推荐