巡回セールスマン問題(逐次改善法)

データ例,プログラム,MT.h

  以下,複数のファイル構成になっています.ファイル間の区切りを「---・・・」で示します.このプログラム例においては,ヘッダファイル MT.h に記述されたメルセンヌ・ツイスタを使用していまが,C++11 で記述可能であれば,標準ライブラリ内に含まれているメルセンヌ・ツイスタ法を使用した乱数生成関数を利用できます.

------------------------ケーススタディデータ------
3
1 data\data10
12 data\data10
123 data\data10

------------------------データファイル------------
都市の数 10 最大試行回数 3000 選択方法(0:最良,1:最初) 1 近傍(2or3) 3
出力レベル(負はファイル) 0 出力方法(-1:なし,0:すべて,1:評価値) 1
出力ファイル名 result\kekka1 表示間隔 0
-58 37
55 -19
6 -79
27 -30
44 -94
33 -58
-94 87
-9 3
33 69
43 -57

------------------------iteration.h---------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "MT.h"

int kyori(int, int *, int **);

/*************************/
/* クラスIterationの定義 */
/*************************/
class Iteration {
		int **city;   //都市の位置データ
		int max_try;   // 最大試行回数
		int n_city;   // 都市の数
		int out_d;   // 表示間隔
		int **rg;   // 都市間の距離
		int *seq_w1;   // 都市を訪れる順序(ワーク)
		int *seq_w2;   // 都市を訪れる順序(ワーク)
		int neib;   // 近傍(2 or 3)
		int out_lvl;   // 出力レベル
                       //   =0 : 最終出力だけ
                       //   n>0 : n回毎に出力(負の時はファイル)
		int out_m;   // 出力方法
                     //   =-1 : 出力しない
                     //   =0 : すべてを出力
                     //   =1 : 評価値だけを出力(最終結果だけはすべてを出力)
		int sel;   // エッジの選択方法
                   //   =0 : 最良のものを選択
                   //   =1 : 最初のものを選択
		char o_file[100];   // 出力ファイル名
	public:
		int *seq;   // 都市を訪れる順序
		Iteration(long, char *);   // コンストラクタ
		Iteration (int, int, int, int, int, int, int, char *, int **);   // コンストラクタ
		Iteration();   // コンストラクタ
		~Iteration();   // デストラクタ
		int Optimize();   // 最適化の実行
		int Change(int *);   // 改善
		void Output(int, int, int);   // 出力
};

------------------------メンバー関数--------------
/*********************************/
/* クラスIterationのメンバー関数 */
/*********************************/
#include "iteration.h"

/****************************/
/* コンストラクタ           */
/*      seed : 乱数の初期値 */
/*      name : ファイル名   */
/****************************/
Iteration::Iteration (long seed, char *name)
{
	double x, y;
	int ct, i1, i2, sw;
	FILE *in;
					// 乱数の初期設定
	init_genrand(seed);
					// ファイルのオープン
	in = fopen(name, "r");
	if (in == NULL) {
		printf("***error  データファイル名が不適当\n");
		exit(1);
	}
					// 基本データ
	fscanf(in, "%*s %d %*s %d %*s %d %*s %d", &n_city, &max_try, &sel, &neib);
	fscanf(in, "%*s %d %*s %d", &out_lvl, &out_m);
	fscanf(in, "%*s %s %*s %d", o_file, &out_d);
					// 都市の位置データ
	city = new int * [n_city];
	for (i1 = 0; i1 < n_city; i1++) {
		city[i1] = new int [2];
		fscanf(in, "%d %d", &city[i1][0], &city[i1][1]);
	}
					// ファイルのクローズ
	fclose(in);
					// 距離テーブルの作成
	rg = new int * [n_city];

	for (i1 = 0; i1 < n_city; i1++) {
		rg[i1] = new int [n_city];
		for (i2 = i1+1; i2 < n_city; i2++) {
			x          = city[i2][0] - city[i1][0];
			y          = city[i2][1] - city[i1][1];
			rg[i1][i2] = (int)(sqrt(x * x + y * y) + 0.5);
		}
	}

	for (i1 = 1; i1 < n_city; i1++) {
		for (i2 = 0; i2 < i1; i2++)
			rg[i1][i2] = rg[i2][i1];
	}
					// 都市を訪れる順序(初期設定)
	seq    = new int [n_city];
	seq_w1 = new int [n_city];
	seq_w2 = new int [n_city];

	for (i1 = 0; i1 < n_city; i1++) {
		sw = 0;
		while (sw == 0) {
			ct = (int)(genrand_real3() * n_city);
			if (ct >= n_city)
				ct = n_city - 1;
			seq[i1] = ct;
			sw      = 1;
			for (i2 = 0; i2 < i1 && sw > 0; i2++) {
				if (ct == seq[i2])
					sw = 0;
			}
		}
	}
}

/******************/
/* コンストラクタ */
/******************/
Iteration::Iteration ()
{
	n_city = 0;
}

/****************/
/* デストラクタ */
/****************/
Iteration::~Iteration ()
{
	int i1;

	if (n_city > 0) {

		for (i1 = 0; i1 < n_city; i1++) {
			delete [] city[i1];
			delete [] rg[i1];
		}
		delete [] city;
		delete [] rg;

		delete[] seq;
		delete [] seq_w1;
		delete [] seq_w2;
	}
}

/****************/
/* 最適化の実行 */
/****************/
int Iteration::Optimize ()
{
	int k1, max, n_tri, sw;
					// 初期設定
	n_tri = 0;
	max   = kyori(n_city, seq, rg);

	if (out_m >= 0 && abs(out_lvl) > 0) {
		printf("***試行回数 %d 距離 %d\n", n_tri, -max);
		Output(out_lvl, n_tri, max);
	}
					// 実行
	sw = 1;
	for (n_tri = 1; n_tri <= max_try && sw > 0; n_tri++) {
						// 改善
		sw = Change(&max);
						// 出力
		if (out_d > 0 && n_tri%out_d == 0)
			printf("***試行回数 %d 距離 %d\n", n_tri, -max);

		if (out_m >= 0 && abs(out_lvl) > 0) {
			if (n_tri%abs(out_lvl) == 0)
				Output(out_lvl, n_tri, max);
		}
	}
					// 最終出力
	if (out_m >= 0) {
		n_tri--;
		k1    = out_m;
		out_m = 0;
		printf("***試行回数 %d 距離 %d\n", n_tri, -max);
		Output(out_lvl, n_tri, max);
		out_m = k1;
	}

	return n_tri;
}

/*******************************/
/* 出力                        */
/*      sw : >=0 : 出力先未定  */
/*           < 0 : ファイル    */
/*      n_tri : 現在の試行回数 */
/*      r : 距離の負値         */
/*******************************/
void Iteration::Output(int sw, int n_tri, int r)
{
	int i1, k = 0, n, pr;
	char *now;
	time_t aclock;
	FILE *out;

	if (sw >= 0) {
		printf("   出力先は(0:出力なし,n:画面にn個づつ,-1:ファイル)? ");
		scanf("%d", &pr);
	}
	else
		pr = -1;

	if (pr != 0) {

		if (pr > 0) {
			out = stdout;
			getchar();
		}
		else {
			time(&aclock);
			now = ctime(&aclock);
			out = fopen(o_file, "a");
			fprintf(out, "***試行回数 %d 距離 %d 時間 %s\n", n_tri, -r, now);
		}

		if (out_m == 0) {
			for (i1 = 0; i1 < n_city; i1++) {
				n = seq[i1];
				fprintf(out, "  %d %d %d\n", n, city[n][0], city[n][1]);
				if (pr > 0) {
					k++;
					if (k == pr) {
						getchar();
						k = 0;
					}
				}
			}
		}

		if (pr <= 0)
			fclose(out);
	}
}

/**************************************/
/* エッジの入れ替え                   */
/*      r_m : 距離の負値              */
/*      return : =0 : 改善がなかった  */
/*               =1 : 改善があった    */
/**************************************/
int Iteration::Change(int *r_m)
{
	int ch = 0, i1, i2, i3, i4, k, k1, k2, max, n1, n2, n3, nn, r, sw = 0;

	max = *r_m;

	n3  = (int)(genrand_real3() * (n_city - 2));
	if (n3 > n_city-3)
		n3 = n_city - 3;
                         // 2近傍
	for (i1 = 0; i1 <= n_city-3 && ch == 0; i1++) {

		if (n3 == 0)
			n1 = n_city - 2;
		else
			n1 = n_city - 1;

		for (i2 = n3+2; i2 <= n1 && ch == 0; i2++) {
                              // 枝の場所((n3,n3+1), (k1,k2))
			k1 = i2;
			if (i2 == n_city-1)
				k2 = 0;
			else
				k2 = i2 + 1;
                              // 枝の入れ替え
			seq_w1[0] = seq[n3];
			k         = 1;
			for (i3 = k1; i3 >= n3+1; i3--) {
				seq_w1[k] = seq[i3];
				k++;
			}

			nn = k2;
			while (nn != n3) {
				seq_w1[k] = seq[nn];
				k++;
				nn++;
				if (nn > n_city-1)
					nn = 0;
			}
                              // 評価
			r = kyori(n_city, seq_w1, rg);

			if (r > max) {
				max = r;
				sw  = 1;
				for (i3 = 0; i3 < n_city; i3++)
					seq_w2[i3] = seq_w1[i3];
				if (sel > 0)
					ch = 1;
			}
		}

		n3++;
		if (n3 > n_city-3)
			n3 = 0;
	}
                         // 3近傍
	if (neib == 3 && ch == 0) {

		for (i1 = 0; i1 <= n_city-3 && ch == 0; i1++) {

			n1 = n_city - 2;
			n2 = n_city - 1;

			for (i2 = n3+1; i2 <= n1 && ch == 0; i2++) {

				for (i3 = i2+1; i3 <= n2 && ch == 0; i3++) {
                              // 枝の場所((n3,n3+1), (i2,i2+1), (k1,k2))
					k1 = i3;
					if (i3 == n_city-1)
						k2 = 0;
					else
						k2 = i3 + 1;
                              // 枝の入れ替えと評価
                                   // 入れ替え(その1)
					seq_w1[0] = seq[n3];
					k         = 1;
					for (i4 = i2; i4 >= n3+1; i4--) {
						seq_w1[k] = seq[i4];
						k++;
					}

					for (i4 = k1; i4 >= i2+1; i4--) {
						seq_w1[k] = seq[i4];
						k++;
					}

					nn = k2;
					while (nn != n3) {
						seq_w1[k] = seq[nn];
						k++;
						nn++;
						if (nn > n_city-1)
							nn = 0;
					}
                                   // 評価(その1)
					r = kyori(n_city, seq_w1, rg);

					if (r > max) {
						max = r;
						sw  = 1;
						for (i3 = 0; i3 < n_city; i3++)
							seq_w2[i3] = seq_w1[i3];
						if (sel > 0)
							ch = 1;
					}
                                   // 入れ替え(その2)
					seq_w1[0] = seq[n3];
					k         = 1;
					for (i4 = k1; i4 >= i2+1; i4--) {
						seq_w1[k] = seq[i4];
						k++;
					}

					for (i4 = n3+1; i4 <= i2; i4++) {
						seq_w1[k] = seq[i4];
						k++;
					}

					nn = k2;
					while (nn != n3) {
						seq_w1[k] = seq[nn];
						k++;
						nn++;
						if (nn > n_city-1)
							nn = 0;
					}
                                   // 評価(その2)
					r = kyori(n_city, seq_w1, rg);

					if (r > max) {
						max = r;
						sw  = 1;
						for (i3 = 0; i3 < n_city; i3++)
							seq_w2[i3] = seq_w1[i3];
						if (sel > 0)
							ch = 1;
					}
                                   // 入れ替え(その3)
					seq_w1[0] = seq[n3];
					k         = 1;
					for (i4 = i2+1; i4 <= k1; i4++) {
						seq_w1[k] = seq[i4];
						k++;
					}

					for (i4 = i2; i4 >= n3+1; i4--) {
						seq_w1[k] = seq[i4];
						k++;
					}

					nn = k2;
					while (nn != n3) {
						seq_w1[k] = seq[nn];
						k++;
						nn++;
						if (nn > n_city-1)
							nn = 0;
					}
                                   // 評価(その3)
					r = kyori(n_city, seq_w1, rg);

					if (r > max) {
						max = r;
						sw  = 1;
						for (i3 = 0; i3 < n_city; i3++)
							seq_w2[i3] = seq_w1[i3];
						if (sel > 0)
							ch = 1;
					}
                                   // 入れ替え(その4)
					seq_w1[0] = seq[n3];
					k         = 1;
					for (i4 = i2+1; i4 <= k1; i4++) {
						seq_w1[k] = seq[i4];
						k++;
					}

					for (i4 = n3+1; i4 <= i2; i4++) {
						seq_w1[k] = seq[i4];
						k++;
					}

					nn = k2;
					while (nn != n3) {
						seq_w1[k] = seq[nn];
						k++;
						nn++;
						if (nn > n_city-1)
							nn = 0;
					}
                                   // 評価(その4)
					r = kyori(n_city, seq_w1, rg);

					if (r > max) {
						max = r;
						sw  = 1;
						for (i3 = 0; i3 < n_city; i3++)
							seq_w2[i3] = seq_w1[i3];
						if (sel > 0)
							ch = 1;
					}
				}
			}

			n3++;
			if (n3 > n_city-3)
				n3 = 0;
		}
	}
                         // 設定
	if (sw > 0) {
		*r_m = max;
		for (i1 = 0; i1 < n_city; i1++)
			seq[i1] = seq_w2[i1];
	}

	return sw;
}

------------------------kyori.cpp-----------------
/*********************************/
/* 距離の計算                    */
/*      n_c : 都市の数           */
/*      p : 都市番号             */
/*      rg : 都市間の距離        */
/*      return : 距離(負)      */
/*********************************/
#include <math.h>

int kyori(int n_c, int *p, int **rg)
{
	int i1, n1, n2, range = 0;

	n1 = p[0];

	for (i1 = 1; i1 < n_c; i1++) {
		n2     = p[i1];
		range -= rg[n1][n2];
		n1     = n2;
	}

	n2     = p[0];
	range -= rg[n1][n2];

	return range;
}

------------------------main----------------------
/****************************/
/* 巡回セールスマン問題     */
/*      反復改善法          */
/*      coded by Y.Suganuma */
/****************************/
#include "iteration.h"

/****************/
/* main program */
/****************/
int main(int argc, char *argv[])
{
	long *seed;
	int i1, n;
	char **i_file;
	FILE *in;
	Iteration *it;
					// 入力ミス
	if (argc <= 1) {
		printf("***error  ファイル名を入力して下さい\n");
		exit(1);
	}
					// 入力OK
	else {
						// ファイルのオープン
		in = fopen(argv[1], "r");
		if (in == NULL) {
			printf("***error  ファイル名が不適当です\n");
			exit(1);
		}
						// 乱数の初期値と入力データファイル名の入力
		fscanf(in, "%d", &n);

		seed   = new long [n];
		i_file = new char * [n];

		for (i1 = 0; i1 < n; i1++) {
			i_file[i1] = new char [100];
			fscanf(in, "%ld %s", &seed[i1], i_file[i1]);
		}

		fclose(in);
						// 実行(乱数の初期値を変える)
		for (i1 = 0; i1 < n; i1++) {
			printf("\n+++++ケース %d+++++\n", i1+1);
							// 入力と初期設定
			it = new Iteration (seed[i1], i_file[i1]);
							// 最適化
			it->Optimize();
		}
	}

	return 0;
}

-----------------------MT.h--------------------

/*
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

/*
   The original version of http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c was modified by Takahiro Omi as
   - delete line 47 "#include<stdio.h>"
   - delete line 174 int main(void){...}
   - change N -> MT_N
   - change N -> MT_N
   - change the file name "mt19937ar.c" -> "MT.h"
*/


/* Period parameters */  
#define MT_N 624
#define MT_M 397
#define MATRIX_A 0x9908b0dfUL   /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mt[MT_N]; /* the array for the state vector  */
static int mti=MT_N+1; /* mti==MT_N+1 means mt[MT_N] is not initialized */

/* initializes mt[MT_N] with a seed */
void init_genrand(unsigned long s)
{
    mt[0]= s & 0xffffffffUL;
    for (mti=1; mti<MT_N; mti++) {
        mt[mti] = 
	    (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); 
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mt[].                        */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mt[mti] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
    int i, j, k;
    init_genrand(19650218UL);
    i=1; j=0;
    k = (MT_N>key_length ? MT_N : key_length);
    for (; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
          + init_key[j] + j; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++; j++;
        if (i>=MT_N) { mt[0] = mt[MT_N-1]; i=1; }
        if (j>=key_length) j=0;
    }
    for (k=MT_N-1; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
          - i; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++;
        if (i>=MT_N) { mt[0] = mt[MT_N-1]; i=1; }
    }

    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
    unsigned long y;
    static unsigned long mag01[2]={0x0UL, MATRIX_A};
    /* mag01[x] = x * MATRIX_A  for x=0,1 */

    if (mti >= MT_N) { /* generate N words at one time */
        int kk;

        if (mti == MT_N+1)   /* if init_genrand() has not been called, */
            init_genrand(5489UL); /* a default initial seed is used */

        for (kk=0;kk<MT_N-MT_M;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+MT_M] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        for (;kk<MT_N-1;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+(MT_M-MT_N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        y = (mt[MT_N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
        mt[MT_N-1] = mt[MT_M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

        mti = 0;
    }
  
    y = mt[mti++];

    /* Tempering */
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680UL;
    y ^= (y << 15) & 0xefc60000UL;
    y ^= (y >> 18);

    return y;
}

/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
    return (long)(genrand_int32()>>1);
}

/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
    return genrand_int32()*(1.0/4294967295.0); 
    /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
    return genrand_int32()*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void) 
{ 
    unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; 
    return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 
/* These real versions are due to Isaku Wada, 2002/01/09 added */