Floyd-Warshall

//Floyd-Warshall algorithm

// If time permits, it can be used very well and is relatively simple

//The core statement of Floyd-Warshall algorithm
	for(int k = 1; k <= n; k++)
	{
		for(int i = 1; i <= n; i++)
		{
			for(int j = 1; j <= n; j++)
			{
				if(e[i][j] > e[i][k] + e[k][j])
				{
					e[i][j] = e[i][k] + e[k][j];
				}
			}
		}
	}

Starting from vertex 1 to find the shortest distance, update the data after the comparison, and then see if it can be added based on 2 to make the route the shortest. Some ideas of dynamic programming are used

# 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];
	const int maxn = 0x3f3f3f3f;
	int n, m;
	//n represents vertices, m represents the number of edges
	cin >> n >> m;
	
	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 a, b, s;
		cin >> a >> b >> s;
		e[a][b] = s;
	}

	//The core statement of Floyd-Warshall algorithm
	for(int k = 1; k <= n; k++)
	{
		for(int i = 1; i <= n; i++)
		{
			for(int j = 1; j <= n; j++)
			{
				if(e[i][j] > e[i][k] + e[k][j])
				{
					e[i][j] = e[i][k] + e[k][j];
				}
			}
		}
	}
	cout << "Output the final result:" << endl;
	// output the final result
	for(int i = 1; i <= n; i++)
	{
		int p = 0;
		for(int j = 1; j <= n; j++)
		{
			if(p++)
			{
				cout << " ";
			}
			cout << e[i][j];
		}
		cout << endl;
	}

	return 0;
	
}
/*
//Input data
4 8
1 2 2
1 3 6
1 4 4
2 3 3
3 1 7
3 4 1
4 1 5
4 3 12




//Final Results
Output the final result:
0 2 5 4
9 0 3 4
6 8 0 1
5 7 10 0
*/



Guess you like

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