POJ 1734 Sightseeing trip

floyd求无向图最小环 +输出路径

注意保存原来的边, 求最小环的时候要用

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <cstring>
using namespace std;
int n, m, dis[105][105], ans = 0x3f3f3f3f, pos[105][105], e[105][105];
int init() {
	int rv = 0, fh = 1;
	char c = getchar();
	while(c < '0' || c > '9') {
		if(c == '-') fh = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		rv = (rv<<1) + (rv<<3) + c - '0';
		c = getchar();
	}
	return fh * rv;
}
vector <int> pat;
void getpath(int x, int y) {
	if(!pos[x][y]) return ;
	getpath(x, pos[x][y]);
	pat.push_back(pos[x][y]);
	getpath(pos[x][y], y);
}
int main() {
	memset(dis, 0x3f, sizeof(dis));
	memset(e, 0x3f, sizeof(e));
	n = init(); m = init();
	for(int i = 1; i <= n; i++) dis[i][i] = 0, e[i][i] = 0;
	for(int i = 1; i <= m; i++) {
		int u = init(), v = init(), di = init();
		e[u][v] = e[v][u] = dis[u][v] = dis[v][u] = min(di, dis[u][v]);
	}
	for(int k = 1; k <= n; k++) {
		for(int i = 1; i < k; i++) {
			for(int j = i + 1; j < k; j++) {
				if(ans > (long long) dis[i][j] + e[k][j] + e[i][k]) {
					ans = (long long) dis[i][j] + e[k][j] + e[i][k];
					pat.clear();
					pat.push_back(i);
					getpath(i, j);
					pat.push_back(j);
					pat.push_back(k);
				}
			}
		}
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				if(dis[i][j] > dis[i][k] + dis[k][j]) {
					dis[i][j] = dis[i][k] + dis[k][j];
					pos[i][j] = k;
				}
			}
		}
	}
	if(ans == 0x3f3f3f3f) printf("No solution.\n");
	else {
		for(int i = 0; i < (int)pat.size(); i++) printf("%d ", pat[i]);
	}
	return 0;
}
posted @ 2018-03-28 15:18  Mr_Wolfram  阅读(147)  评论(0编辑  收藏  举报