C++ 程式來實現最近鄰演算法
這是一個 C++ 程式,用以實現最近鄰演算法,此演算法用於實現旅行商問題,以計算僅遍歷一次邊時訪問所有節點所需的最小成本。
所需函式和虛擬碼
演算法
Begin Initialize c = 0, cost = 1000; Initialize g[][]. function swap() is used to swap two values x and y. function cal_sum() to calculate the cost which take array a[] and size of array as input. Initialize sum =0. for i = 0 to n compute s+= g[a[i %3]][a[(i+ 1) %3]]; if (cost >s) cost = s function permute() is used to perform permutation: If there is one lement in array call cal_sum(). else for j = i to n swap (a+i) with (a + j) cal_sum(a+1,n) swap (a+i) with (a + j) End
示例程式碼
#include<iostream>
using namespace std;
int c = 0, cost = 1000;
int g[3][3 ] = { {1,2,3},{4,5,8},{6,7,10}};
void swap(int *x, int *y) {
int t;
t = *x;
*x = *y;
*y = t;
}
void cal_sum(int *a, int n) {
int i, s= 0;
for (i = 0; i <= n; i++) {
s+= g[a[i %3]][a[(i+ 1) %3]];
}
if (cost >s) {
cost = s;
}
}
void permute(int *a,int i,int n) {
int j, k;
if (i == n) {
cal_sum (a,n);
} else {
for (j = i; j <= n; j++) {
swap((a + i), (a + j));
cal_sum(a+1,n);
swap((a + i), (a + j));
}
}
}
int main() {
int i, j;
int a[] = {1,2,3};//take array elements
permute(a, 0,2);
cout << "minimum cost:" << cost << endl;
}輸出
minimum cost:3
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP