Dijkstra algorithm (1) --- the shortest path (template)

description:

The two integers n and m in the first line represent the number of vertices (numbered from 1 to n), and m represents the number of edges. In the next m rows, each row has 3 numbers x, y, z, which express the weight of the edge from vertex x to vertex y as z.

Sample

enter:

6	9
1	2	1
1	3	12
2	3	9
2	4	3
3	5	5
4	3	4
4	5	13
4	6	15
5	6	4

Output:0 1 8 4 13 17

Code:

#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f; //定义无穷大

int main(){
    
    
	//freopen("a.txt","r",stdin);
	int n,m,e[200][200],d[200],vis[200],min;
	//n为顶点个数,m为边的数目,e为邻接矩阵,d为最短路数组,vis标记节点是否访问过,min为最小值
	cin>>n>>m;
	int u,v,k;
	memset(d,INF,sizeof d);
	memset(e,INF,sizeof e);
	memset(vis,0,sizeof vis); 
	for(int i = 1;i<=m;i++){
    
    
		cin>>u>>v>>k;
		e[u][v] = k;
	}
	//读入边
	//以下为核心:
	//一、 初始化,将出发点到自身的距离设置为0
	d[1] = 0;
	//二、循环n(顶点个数)次
	for(int i =1;i<=n;i++){
    
    
	//三、将最小值设置为无穷大,方便寻找最小值
		min = INF;
	//四、循环n次,每次都寻找当前未访问过顶点中的路径最小的顶点
		for(int j = 1;j<=n;j++){
    
    
			if(vis[j] == 0&& d[j] < min){
    
    
				min = d[j];
				u = j;
			}
		}
	//五、将寻找到的当前路径最小点设置为已经访问
		vis[u]  = 1;
	//六、判断是否可以优化
		for(v = 1;v<= n;v++){
    
    
			if(vis[v] ==0 && e[u][v]<INF ){
    
    
				if( d[u] + e[u][v] < d[v]){
    
    
					d[v] = d[u] + e[u][v];
				}
			}
		}
	}
	//输出
	for(int i = 1;i<=n;i++){
    
    
		cout<<d[i]<<' ';
	}
	return 0;
}

end.

Guess you like

Origin blog.csdn.net/m0_45210226/article/details/105924189