The shortest path algorithm outputs Dijstra

1. Before we can use Dijstra algorithm for solving the shortest distance to reach the rest of the vertices from the source point, then how to solve the source point to reach the v vertices of the shortest distance through which it?

2. The execution of the algorithm is as follows:

① actually very simple, we only need to add on a pre array based on the original use Dijstra algorithm shortest distance from the recorded previous node the shortest distance from the source point s to the vertex v in, so if we find through intermediate vertices u such that the shorter the time may be recorded before it reaches a vertex on the shortest path from the source vertex v s distance from the source point to the vertex v

② When Dijstra algorithm ends, then the front from the source s to the rest of the shortest distance from the apex experienced in a vertex we recorded, but we just solved precursor each vertex on the shortest path, how to solve the complete trails?

pre[4] = 3;
pre[3] = 2;
pre[2] = 1;
pre[1] = 1;

When we want to know the shortest path to reach the starting point v1 v4, we need to start with the pre [4], a precursor node v3 v4, and [3] to obtain the precursor node v3 v2 from pre, and then from the pre [2] obtained precursor v2 node v1, in fact, this is a recursive process, continue to use the information to find pre precursor

 

3. The specific code as follows:

#include<cstdio>
#include<iostream>
using namespace std;
const int maxSize = 1000;
const int INF = 100000000;
int n, m, s, G[maxSize][maxSize];
int d[maxSize];
bool vis[maxSize] = {false};
//pre[v]数组表示从起点到顶点v的最短路径上v的前一个顶点 
int pre[maxSize];
void Dijstra(int s){
	fill(d, d + maxSize, INF);
	d[s] = 0;
	for(int i = 0; i < n; i++){
		int u = -1, min = INF;
		for(int j = 0; j < n; j++){
			if(vis[j] == false && d[j] < min){
				u = j;
				min = d[j];
			}
		}
		if(u == -1) return;
		vis[u] = true;
		for(int v = 0; v < n; v++){
			if(vis[v] == false && G[u][v] != INF && d[u] + G[u][v] < d[v]){
				d[v] = d[u] + G[u][v];
				pre[v] = u;	
			}
		}
	}	
}

//输出源点到顶点v的最短路径
void shortPath(int s, int v){
	if(s == v){
		//相等的时候说明已经找到了第一个节点可以层层返回进行输出 
		cout << s << " ";
		return;
	}
	shortPath(s, pre[v]);
	cout << v << " "; 
}

int main(void){
	int u, v, w;
	cin >> n >> m >> s;
	//初始化的时候将每个顶点的前驱设置为自己
	for(int i = 0; i < n; ++i) pre[i] = i;
	fill(G[0], G[0] + maxSize * maxSize, INF);
	for(int i = 0; i < m; i++){
		cin >> u >> v >> w;
		G[u][v] = w;
	}
	Dijstra(s);
	for(int i = 0; i < n; i++){
		cout << d[i] << " ";
	}
//	cout << endl;
	//使用递归的方法来输出其中的最短路径 
	//输入v顶点 
	cin >> v;
//	cout << s << " " << v << endl;  
	shortPath(s, v);
}

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/93207838
Recommended