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; 
}


你可能感兴趣的:(Algorithm,C++,动态规划)