Program work 9. Traveling salesman problem (TSP)

来源:互联网 发布:大城市生活 知乎 编辑:程序博客网 时间:2024/05/16 23:48

开发环境: Linux 14.04 LTS 

编译器: g++ 

开发工具: Eclipse 

开发语言: c++ 


输入为8个文件: (每个文件包含有向权图. 且a→b和b→a的权值不同. 没有自环, 数字表示城市个数) 

TSP5.txt 

TSP10.txt 

TSP20.txt 

TSP50.txt 

TSP100.txt 

TSP250.txt 

TSP500.txt 

TSP1000.txt


程序思路:贪婪法则步骤如下: 

1. 假如有n个城市, 从第1个城市为起点. 

2. 找到与当前城市相连的城市中cost最小的城市b, 并将此cost加入到总cost中. 

3. 走到城市b, 当前城市为b. 重复步骤2, 直到已经没有城市可走 

4. 得到总cost. 

5. 回到步骤1, 以第2个城市为起点, 直到以所有城市为起点都跑完. 

6. 因为分别以n个城市为起点都走了一遍, 会得到n个总cost, 从n个总cost中选出最小的, 作为结果. 

疑问:能保证每个城市都只走一次不会重复? 

回答:可以. 在程序实现过程中,用了一个数组标识城市是否走过. 所以每次选最小cost都是从尚未走过的成城市中选出来的. 


时间复杂度 O(n^3次方) 不确定是最优解, 但跟其它同学相较下确实得到的cost比他们都小不只一点.

//============================================================================// Name        : sicily.cpp// Author      : Reid Chan// Version     :// Copyright   : Your copyright notice//============================================================================#include <iostream>#include <fstream>#include <cstdlib>#include <string>using namespace std;int cost[1000][1000];/** * read the file's data into 2d arrays. */void init(int &row, string name) {/***** calculate the row number of the file which means the number of cities *****/ifstream infile;// loop until the file is exist.while (true) {infile.open(name.c_str());if (!infile) {cout << "invalid file name." << endl;} elsebreak;}string line;while (getline(infile, line)) {row++;}infile.close();/***** read data from file, cost[][] is the initial array *****/infile.open(name.c_str());string temp;for (int i = 0; i < row; i++) {for (int j = 0; j < row; j++) {infile >> temp;cost[i][j] = atoi(temp.c_str());}}infile.close();}/** * for each source compute its min cost from his neighbour */void getCost(int *visited, int &minCost, int source, int row) {visited[source] = 1;int count = 1;int next = -1;int i = source;int sum = 0;while (count < row) {int min = 99999999;for (int j = 0; j < row; j++) {if (visited[j] == 0 && cost[i][j] < min) {min = cost[i][j];next = j;}}sum += min;visited[next] = 1;i = next;count++;if (sum > minCost) {return;}}minCost = sum;}void initVisited(int *v, int r) {for (int i = 0; i < r; i++) {v[i] = 0;}}int main() {string file[8] = { "TSP5.txt", "TSP10.txt", "TSP20.txt", "TSP50.txt","TSP100.txt", "TSP250.txt", "TSP500.txt", "TSP1000.txt" };for (int k = 0; k < 8; k++) {int row = 0;init(row, file[k]);int *visited = new int[row];initVisited(visited, row);int minCost = 99999999;for (int i = 0; i < row; i++) {getCost(visited, minCost, i, row);initVisited(visited, row);}cout << file[k] << "'s min cost is: " << minCost << endl;delete[] visited;}return 0;}


0 0
原创粉丝点击