最短路径_Floyd算法

// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。
//
/*
6 9
0 1 34
0 5 19
0 2 46
2 5 25
2 3 17
5 3 25
5 4 26
3 4 38
1 4 12
*/
/*
5 7
0 1 10
1 2 50
3 2 20
2 4 10
3 4 60
0 3 30
0 4 100
*/

#include "stdafx.h"
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int n, m;
int map[50][50] = { 0 };
int dist[50][50] = { 0 };
string path[50][50];

string trans(int p, int q)
{
	string x;
	string y;
	string a;
	stringstream ss, tt;
	ss << p; ss >> x;
	tt << q; tt >> y;
	a = x + y;
	//cout << x << "+" << y << "=" << a<<endl;
	return a;
}
void create()
{
	cin >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int x, y;
		cin >> x >> y; cin >> map[x][y];
		//map[y][x] = map[x][y];//无向图
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			path[i][j] = ((map[i][j] == 0) ? "" : (trans(i, j)));
		}
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			dist[i][j] = ((map[i][j] == 0) ? 0xffffff : map[i][j]);
		}
	}
}

void floyd()//!!
{
	for (int k = 0; k < n; k++)
	{
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (dist[i][j] > dist[i][k] + dist[k][j])
				{
					dist[i][j] = dist[i][k] + dist[k][j];
					path[i][j] = path[i][k] + path[k][j];
				}
			}
		}
	}
}

void print()
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (dist[i][j] == 0xffffff)
				cout << i << "->" << j << ":" << "∞" << "    " << path[i][j] << endl;
			else
				cout << i << "->" << j << ":" << dist[i][j] << "    " << path[i][j] << endl;
		}
	}

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (dist[i][j] == 0xffffff)
				cout << "∞" << " ";
			else
				cout << dist[i][j] << " ";
		}
		cout << endl;
	}
}

int main()
{
	create();
	floyd();
	print();
}

猜你喜欢

转载自blog.csdn.net/qq_32259423/article/details/80823569