A星算法解决TSP问题
2017-05-09 10:38
981 查看
TSP问题相信大部分人已经很熟悉了,就直接展示解法了
#include<iostream> #include<cmath> #include <vector> using namespace std; double dis(int a[], int b[]) { double x1 = a[0]; double y1 = a[1]; double x2 = b[0]; double y2 = b[1]; double x = pow(x1 - x2, 2); double y = pow(y1 - y2, 2); return sqrt(x + y); } //double f(int start, int next){ // //} int main() { int city[10][2]; for (int i = 0; i < 10; i++) for (int j = 0; j < 2; j++) cin >> city[i][j]; int start; cin >> start;//start-1 = 起始 double discity[10][10];//距离矩阵 for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) { if (i == j) discity[i][j] = 999; else discity[i][j] = dis(city[i], city[j]); } int step[20];//用于存储已访问过的城市 int arrived[10] = { 0 }; step[0] = start - 1; double sum = 0; int cur = step[0]; arrived[step[0]] = 1; int next; int count = 1; while (count<10) { cur = step[count - 1]; int min = 9999; for (int i = 0; i < 10; i++){ if (arrived[i] == 0) { if (min > discity[cur][i] + discity[start][i]) { min = discity[cur][i] + discity[start][i]; next = i; } } } arrived[next] = 1; sum += discity[cur][next]; //cout << sum << endl; //cout << discity[cur][next] << endl; step[count] = next; count++; //cout << sum<<endl; } sum += discity[cur][next]; for (int i = 0; i < 10;i++) { cout << step[i] +1<<"->"; } cout << start << endl; cout << sum << endl; //cout << "No output." << endl; system("pause"); return 0; //1 2 3 7 4 9 5 1 2 8 4 6 3 8 9 1 8 8 4 4 //5 }
相关文章推荐
- 遗传算法解决TSP问题实现以及与最小生成树的对比
- SA:利用SA算法解决TSP(数据是14个虚拟城市的横纵坐标)问题——Jason niu
- 遗传算法解决TSP问题实现以及与最小生成树的对比
- 利用遗传算法解决TSP问题
- 概率种群遗传算法解决TSP问题
- 蚁群算法解决TSP问题
- ACO蚁群算法解决TSP旅行商问题
- 在matlab上实现遗传算法解决TSP旅行者问题
- 遗传算法解决TSP问题实现以及与最小生成树的对比
- 用遗传算法解决TSP问题
- “人民币找零”问题的贪婪法解决算法
- 解决排列组合问题的通用算法
- “装箱”问题的贪婪法解决算法
- “循环赛日程安排”问题的分而治之解决算法
- “马的遍历”问题的贪婪法解决算法
- “循环赛日程安排”问题的分而治之解决算法
- 关于用C#实现蚁群算法解决TSP问题
- “人民币找零”问题的贪婪法解决算法
- (原創) 解决问题时,不要只从演算法的角度去思考 (日記)
- “马的遍历”问题的贪婪法解决算法