POJ 1734.Sightseeing trip(Floyd 최소 루프)

1495 단어 floyd
Floyd 최소환 템플릿 문제
code
/*

       floyd   ,    ,     O(n^3)

             

*/

#include <iostream>

#include <cstring>

using namespace std;

const int INF = 109, maxn = 252645135;

int g[INF][INF], dis[INF][INF], pre[INF][INF];

int ans[INF];

//pr[i][j]  i j         

int n, m, tem , tol;

int main() {

	while (cin >> n >> m) {

		tem = maxn;

		memset (g, 0xf, sizeof g);

		memset (dis, 0xf, sizeof dis);

		memset (pre, 0, sizeof pre);

		int x, y, z;

		for (int i = 1; i <= m; i++) {

			cin >> x >> y >> z;

			if (z < g[x][y])

				dis[x][y] = dis[y][x] = g[x][y] = g[y][x] = z;

			pre[x][y] = y, pre[y][x] = x;

		}

		for (int k = 1; k <= n; k++) {

			for (int i = 1; i < k; i++)

				for (int j = i + 1; j < k; j++) {

					if (tem > dis[i][j] + g[i][k] + g[k][j]) {

						tem = dis[i][j] + g[i][k] + g[k][j];

						int t = i;

						tol = 0;

						while (t != 0) {

							ans[++tol] = t;

							t = pre[t][j];

						}

						ans[++tol] = k;

					}

				}

			for (int i = 1; i <= n; i++)

				for (int j = 1; j <= n; j++)

					if (i != j && dis[i][k] + dis[k][j] < dis[i][j]) {

						dis[i][j] = dis[i][k] + dis[k][j];

						pre[i][j] = pre[i][k];

					}

		}

		if (tem == maxn) cout << "No solution.";

		else

			for (int i = 1; i <= tol; i++)

				cout << ans[i] << ' ';

		cout << endl;

	}

	return 0;

}


좋은 웹페이지 즐겨찾기