最近傍アルゴリズムを使用して巡回セールスマン問題を実装する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 element 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};
permute(a, 0,2);
cout << "minimum cost:" << cost << endl;
} 出力
Comparing str1 and str2 using ==, Res: 0 Comparing str1 and str3 using ==, Res: 1 Comparing str1 and str2 using compare(), Res: -1024 Comparing str1 and str3 using compare(), Res: 0>
-
動的計画法を使用してナップサック問題を解決するC++プログラム
これは、動的計画法を使用して0-1ナップサック問題を解決するC++プログラムです。 0-1ナップサック問題では、それぞれに重みと値を持つアイテムのセットが与えられます。合計重量が指定された制限以下になり、合計値が可能な限り大きくなるように、コレクションに含める各アイテムの数を決定する必要があります。 アルゴリズム Begin Input set of items each with a weight and a value Set knapsack capacity Create a function that returns maximum of two integers. Create a
-
ヒープソートアルゴリズムを使用して10個の要素の配列をソートするC++プログラム
ヒープソートは、バイナリヒープデータ構造に基づいています。バイナリヒープでは、親ノードの子ノードは最大ヒープの場合はそれ以下であり、親ノードの子ノードは最小ヒープの場合はそれ以上です。 ヒープソートのすべてのステップを説明する例は次のとおりです。 並べ替え前の10個の要素を含む元の配列は-です 20 7 1 54 10 15 90 23 77 25 この配列は、max-heapifyを使用してバイナリ最大ヒープに組み込まれています。配列として表されるこの最大ヒープは、次のように与えられます。 90 77 20 54