main(int argc, char *argv[]) { int n; // 点の数 struct point p[MAX_N]; // 各点の座標を表す配列 int tour[MAX_N]; // 巡回路を表現する配列 if(argc != 2) { fprintf(stderr,"Usage: %s <tsp_filename>\n",argv[0]); exit(EXIT_FAILURE); } // 点の数と各点の座標を1番目のコマンドライン引数で指定されたファイルから読み込む read_tsp_data(argv[1],p, &n); // 最近近傍法による巡回路構築 nn(p,n,tour); // 巡回路をテキストファイルとして出力 write_tour_data("tour1.dat",n,tour); // 巡回路長を画面に出力 printf("%lf\n",tour_length(p,n,tour)); // 2opt による改善 TwoOpt(p,n,tour); // 巡回路をテキストファイルとして出力 write_tour_data("tour2.dat",n,tour); // 巡回路長を画面に出力 printf("%lf\n",tour_length(p,n,tour)); exit(EXIT_SUCCESS); }
Tour * tour_mutate(Tour *old_tour) { town_index_t i, num_vertexes; TownPool *tp; Tour * new_tour; num_vertexes = old_tour->town_list->config.num_vertexes; tp = tp_new(num_vertexes); new_tour = new_empty_tour(old_tour->town_list, num_vertexes); #pragma omp parallel for for (i=0; i<num_vertexes; i++){ new_tour->tour[i] = old_tour->tour[i]; } { town_index_t i1, i2; i1 = (town_index_t)tp_random_town(tp); i2 = (town_index_t)tp_random_town(tp); new_tour->tour[i1] = old_tour->tour[i2]; new_tour->tour[i2] = old_tour->tour[i1]; } new_tour->length = tour_length(new_tour); tp_destroy(tp); return new_tour; }
Tour * tour_new(TownList *towns) { town_index_t i, num_vertexes = towns->config.num_vertexes; TownPool *tp = tp_new(num_vertexes); if (!tp) exit(1); Tour * newtour = new_empty_tour(towns, num_vertexes); for (i=0; i<num_vertexes; i++){ newtour->tour[i] = tp_random_town(tp); } newtour->length = tour_length(newtour); tp_destroy(tp); return newtour; }
int main(int argc, char *argv[]) { graph g = read_kattis(); if(g.n <= 3) // all solutions identical { for(size_t i = 0 ; i < g.n; ++i) printf("%d\n", i); graph_free(g); return 0; } // k neighbours can't be more than neighbours available if(g.n-1 < k) k = g.n-1; /* fputs("[distance matrix]\n", stderr); for(size_t i = 0; i < g.n; ++i) { for(size_t j = 0; j < g.n; ++j) fprintf(stderr, "%3d ", graph_get_dist(g, i, j)); fputc('\n', stderr); } fputs("\n[neighbour matrix]\n", stderr); for(size_t i = 0; i < g.n; ++i) { for(size_t j = 0; j < g.n; ++j) fprintf(stderr, "%3d ", graph_get_neighbour(g, i, j)); fputc('\n', stderr); }*/ size_t greedy[g.n]; greedy_tsp(g, greedy); greedy_tour = greedy; fprintf(stderr, "\n[greedy tour]\n"); print_tour(g, greedy); size_t tour[g.n]; size_t tour2[g.n]; for(size_t i = 0; i < g.n; ++i) tour2[i] = greedy[i]; size_t *tour_ptr = tour; size_t *best = tour2; fprintf(stderr, "\n[tours]\n"); for(size_t i = 0; i < 14; ++i) { solve_tsp(g, tour_ptr); print_tour(g, tour_ptr); if(tour_length(g, tour_ptr) < tour_length(g, best)) { size_t *tmp = best; best = tour_ptr; tour_ptr = tmp; } } fprintf(stderr, "\n[kattis (best)]\n"); print_kattis(g, best); fprintf(stderr, "[kattis length: %d]\n", tour_length(g,best)); graph_free(g); return 0; }
void print_tour(graph g, size_t *tour) { for(size_t i = 0; i < g.n; ++i) fprintf(stderr, "%d->", tour[i]); fprintf(stderr, "%d (%d)\n", tour[0], tour_length(g, tour)); }