programming-challenges Unidirectional TSP (111104) 题解

http://algorithmist.com/index.php/UVa_116 这里有很好的测试用例。这道题其实只是很直观的迭代。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

const int N = 110, M = 20; 
long long a[M][N]; 

struct Rec {
	vector<int> path; 
};
bool operator<(const Rec& rec1, const Rec& rec2) {
	for (int i = 0; i < rec1.path.size(); i++) {
		if (rec1.path[i] < rec2.path[i]) return true;
		if (rec1.path[i] > rec2.path[i]) return false;
	}
	return false; 
}

vector<Rec> paths(M); 

int main() {
	int m, n; 

	while (cin >> m) {
		cin >> n; 
		memset(a, 0, sizeof(a));
		paths.clear();
		paths.resize(M);

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				cin >> a[i][j]; 
			}
		}

		for (int i = 0; i < m; i++) {
			paths[i].path.push_back(i);
		}

		for (int i = 1; i < n; i++) {
			vector<Rec> tempPaths(M);
			for (int j = 0; j < m; j++) {
				long long minVal = a[(j + m - 1) % m][i-1] + a[j][i];
				int row = (j + m - 1) % m; 
				for (int k = 0; k <= 1; k++) {
					long long val = a[(j + m + k) % m][i-1] + a[j][i];
					if (val < minVal) {
						minVal = val; 
						row = (j + m + k) % m; 
					}
					else if (val == minVal) {
						int newRow = (j + m + k) % m; 
						if (paths[row].path > paths[newRow].path) {
							row = newRow; 
						} 
					}
				}
				tempPaths[j] = paths[row];
				tempPaths[j].path.push_back(j); 
				a[j][i] = minVal; 
			}
			paths = tempPaths;
		}

		long long obj = 0x7fffffffffffffff; 
		for (int i = 0; i < m; i++) {
			obj = obj < a[i][n - 1] ? obj : a[i][n - 1];
		}

		bool firstPath = true;
		Rec bestPath; 
		for (int i = 0; i < m; i++) {
			if (a[i][n - 1] == obj) {
				if (firstPath) {
					firstPath = false;
					bestPath = paths[i];
				}
				else {
					bestPath = min(bestPath, paths[i]);
				}
			}
		}

		for (int i = 0; i < bestPath.path.size(); i++) {
			cout << bestPath.path[i] + 1;

			if (i + 1 < bestPath.path.size())
				cout << " ";
		}
		cout << endl << obj << endl; 
	}

	return 0; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值