Dijkstra

/*
The meaning of the shortest distance is different in the network diagram and the non-network diagram
- The network graph is the path with the least sum of weights on the edges that the two vertices pass through
-A non-network graph is the path with the least number of edges passing between two vertices
*/


# include <iostream>
# include <numeric>
# include <algorithm>
# include <functional>
# include <list>
# include <map>
# include <set>
# include <stack>
# include <deque>
# include <queue>
# include <vector>
# include <ctime>
# include <cstdlib>
# include <cmath>
# include <string>


using namespace std;
int main(int argc, char  *argv[])
{
	int e[10][10], dis[10], book[10], n, m;
	const int maxn = 0x3f3f3f3f;
	//Read in n and m, n represents the number of vertices, m represents the number of edges.
	scanf("%d %d", &n, &m);


	//initialization
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(i == j)
			{
				e[i][j] = 0;
			}
			else
			{
				e[i][j] = maxn;
			}
		}
	}


	// read in edge
	for(int i = 1; i <= m; i++)
	{
		int t1, t2, t3;
		cin >> t1 >> t2 >> t3;
		e [t1] [t2] = t3;
	}
	//Initialize the dis array, here is the initial path from vertex 1 to the rest of the vertices
	for(int i = 1; i <= n; i++)
	{
		dis [i] = e [1] [i];
	}
	//initialize the book array
	memset(book, 0, sizeof(book));
	book[1] = 1;
	//The core statement of Dijkstra's algorithm
	//The big loop means to execute n-1 to find the shortest distance
	for(int i = 1; i <= n - 1; i++)
	{
		//find the vertex closest to vertex 1
		int min = maxn;
		int flag;
		for(int j = 1; j <= n; j++)
		{
			if(!book[j] && dis[j] < min)
			{
				//Record the minimum value and subscript
				min = dis [j];
				flag = j;
			}
		}
		book[flag] = 1;
		//Find the subscript of the current shortest vertex and relax.
		for(int v = 1; v <= n; v++)
		{
			if(e[flag][v] < maxn)
			{
				if(dis[v] > dis[flag] + e[flag][v])
				{
					dis [v] = dis [flag] + e [flag] [v];
				}
			}
		}
	}


	for(int i = 1; i <= n; i++)
	{
		if(i == n)
		{
			cout << dis[i] << endl;
		}
		else
		{
			cout << dis[i] << " ";
		}
	}


	return 0;


}


/*
Input data
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


*/
-+

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735434&siteId=291194637