]> git.sesse.net Git - nms/blob - tsp/tsp.cpp
Add gap calculation to the distances in the TSP solver.
[nms] / tsp / tsp.cpp
1 #include <stdio.h>
2 #include <limits.h>
3 #include <vector>
4 #include <set>
5 #include <algorithm>
6
7 #define MIN_ROW 1
8 #define MAX_ROW 75
9 #define MIN_SWITCH 1
10 #define MAX_SWITCH 6
11 #define HEAP_MST 0
12
13 static const unsigned num_cache_elem = (MAX_ROW * MAX_SWITCH * 2) * (MAX_ROW * MAX_SWITCH * 2);
14 static unsigned short dist_cache[(MAX_ROW * MAX_SWITCH * 2) * (MAX_ROW * MAX_SWITCH * 2)],
15         opt_dist_cache[MAX_ROW * MAX_SWITCH * MAX_ROW * MAX_SWITCH],
16         pess_dist_cache[MAX_ROW * MAX_SWITCH * MAX_ROW * MAX_SWITCH];
17
18 inline unsigned short &cache(
19         unsigned row_from, unsigned switch_from, unsigned side_from,
20         unsigned row_to, unsigned switch_to, unsigned side_to)
21 {
22         return dist_cache[(row_from * MAX_SWITCH * 2 + switch_from * 2 + side_from) * (MAX_ROW * MAX_SWITCH * 2) +
23                 row_to * MAX_SWITCH * 2 + switch_to * 2 + side_to];
24 }
25
26 inline unsigned short &opt_cache(
27         unsigned row_from, unsigned switch_from,
28         unsigned row_to, unsigned switch_to)
29 {
30         return opt_dist_cache[(row_from * MAX_SWITCH + switch_from) * (MAX_ROW * MAX_SWITCH) +
31                 row_to * MAX_SWITCH + switch_to];
32 }
33
34 inline unsigned short &pess_cache(
35         unsigned row_from, unsigned switch_from,
36         unsigned row_to, unsigned switch_to)
37 {
38         return pess_dist_cache[(row_from * MAX_SWITCH + switch_from) * (MAX_ROW * MAX_SWITCH) +
39                 row_to * MAX_SWITCH + switch_to];
40 }
41
42 struct order {
43         unsigned row, num;
44         int side;
45         int cost;
46
47         bool operator< (const order &other) const
48         {
49                 return (cost < other.cost);
50         }
51 };
52
53 static unsigned best_so_far = UINT_MAX;
54 order *best_tour;
55
56 int distance_switch(unsigned from, unsigned to)
57 {
58         /* on the same side of the middle? 9.6m per switch. */
59         if ((from > 3) == (to > 3)) {
60                 return abs(from - to) * 96;
61         }
62
63         /* have to cross the border? 25.8m from sw3->sw4 => 16.2m extra gap. */
64         /* that's _got_ to be wrong. say it's 3m. */
65         return abs(from - to) * 96 + 30;
66 }
67
68 int distance_middle(unsigned sw, unsigned middle)
69 {
70         /* symmetry: 4-5-6 are just mirrored 3-2-1. */
71         if (middle == 2) {
72                 if (sw > 3)
73                         sw = 7 - sw;
74
75                 /* estimate 25.8m/2 = 12.9m from sw3 to the middle */
76                 return 129 + (3 - sw) * 96;
77         }
78         
79         /* more symmetry -- getting from 1-6 to the top is like getting from 6-1 to the bottom. */
80         if (middle == 3) {
81                 middle = 1;
82                 sw = 7 - sw;
83         }
84
85         /* guesstimate 4.8m extra to get to the bottom */
86         if (sw > 3)
87                 return 48 + 162 + (sw - 1) * 96;
88         else
89                 return 48 + (sw - 1) * 96;
90 }
91
92 int distance_row(unsigned from, unsigned to)
93 {
94         /* 4.1m per double row, plus gaps */
95         unsigned base_cost = 41 * abs(from - to);
96         
97         if ((from <= 9) != (to <= 9))
98                 base_cost += 25;
99         if ((from <= 17) != (to <= 17))
100                 base_cost += 25;
101         if ((from <= 25) != (to <= 25))
102                 base_cost += 25;
103         if ((from <= 34) != (to <= 34))
104                 base_cost += 25;
105
106         /* don't calculate gaps here just yet, just estimate 4.1m per double row */
107         return base_cost;
108 }
109
110 int pessimistic_distance(int row_from, int switch_from, int row_to, int switch_to)
111 {
112         /* we'll need to go to one of the three middles */
113         int best2 = distance_middle(switch_from, 2) + distance_middle(switch_to, 2);
114         int distrow = distance_row(row_from, row_to);
115         if ((switch_from > 3) != (switch_to > 3))
116                 return best2 + distrow;
117         if (switch_from > 3) {
118                 int best3 = distance_middle(switch_from, 3) + distance_middle(switch_to, 3);
119                 return std::min(best2, best3) + distrow;
120         } else {
121                 int best1 = distance_middle(switch_from, 1) + distance_middle(switch_to, 1);
122                 return std::min(best2, best1) + distrow;
123         }
124 }
125
126 int distance(int row_from, int switch_from, int side_from, int row_to, int switch_to, int side_to)
127 {
128         /* can we just walk directly? */
129         if (row_from == row_to && side_from == side_to) {
130                 return distance_switch(switch_from, switch_to);
131         }
132         
133         /* can we just switch sides? */
134         if (row_from + 1 == row_to && side_from == 1 && side_to == 0) {
135                 return distance_switch(switch_from, switch_to);
136         }
137         if (row_from == row_to + 1 && side_from == 0 && side_to == 1) {
138                 return distance_switch(switch_from, switch_to);
139         }
140
141         return pessimistic_distance(row_from, switch_from, row_to, switch_to);
142 }       
143
144 int optimistic_distance(int row_from, int switch_from, int row_to, int switch_to)
145 {
146         if (abs(row_from - row_to) <= 1)
147                 return distance_switch(switch_from, switch_to);
148         else
149                 return pessimistic_distance(row_from, switch_from, row_to, switch_to);
150 }
151
152 #if HEAP_MST
153 // this is, surprisingly enough, _slower_ than the naive variant below, so it's not enabled
154 struct prim_queue_val {
155         std::pair<unsigned, unsigned> dst;
156         int cost;
157
158         bool operator< (const prim_queue_val &other) const
159         {
160                 return (cost > other.cost);
161         }
162 };
163
164 // standard O(V^2 log v) prim
165 int prim_mst(std::set<std::pair<unsigned, unsigned> > &in)
166 {
167         std::set<std::pair<unsigned, unsigned> > set2;
168         std::priority_queue<prim_queue_val> queue;
169
170         // pick the first one
171         std::set<std::pair<unsigned, unsigned> >::iterator start = in.begin();
172         
173         unsigned row = start->first;
174         unsigned num = start->second;
175
176         set2.insert(*start);
177         
178         // find all the edges out from it
179         for (std::set<std::pair<unsigned, unsigned> >::iterator j = in.begin(); j != in.end(); ++j) {
180                 if (set2.count(*j))
181                         continue;
182                 
183                 unsigned d = opt_cache(row, num, j->first, j->second);
184                 prim_queue_val val = { *j, d };
185                 queue.push(val);
186         }
187
188         unsigned total_cost = 0;
189         while (set2.size() != in.size()) {
190 invalid:
191                 prim_queue_val val = queue.top();
192                 queue.pop();
193                 
194                 // check if dst is already moved
195                 if (set2.count(val.dst))
196                         goto invalid;
197         
198                 unsigned row = val.dst.first;
199                 unsigned num = val.dst.second;
200                 set2.insert(val.dst);
201
202                 total_cost += val.cost;
203
204                 // find all the edges from this new node
205                 for (std::set<std::pair<unsigned, unsigned> >::iterator j = in.begin(); j != in.end(); ++j) {
206                         if (set2.count(*j))
207                                 continue;
208                         
209                         unsigned d = opt_cache(row, num, j->first, j->second);
210                         prim_queue_val val = { *j, d };
211                         queue.push(val);
212                 }
213         }
214
215         return total_cost;
216 }
217 #else
218 // extremely primitive O(V^3) prim
219 int prim_mst(std::set<std::pair<unsigned, unsigned> > &set1)
220 {
221         std::set<std::pair<unsigned, unsigned> > set2;
222
223         // pick the first one
224         std::set<std::pair<unsigned, unsigned> >::iterator start = set1.begin();
225         set2.insert(*start);
226         set1.erase(start);
227
228         unsigned total_cost = 0;
229         while (set1.size() > 0) {
230                 unsigned best_this_cost = UINT_MAX;
231                 std::set<std::pair<unsigned, unsigned> >::iterator best_set1;
232                 
233                 for (std::set<std::pair<unsigned, unsigned> >::iterator i = set1.begin(); i != set1.end(); ++i) {
234                         for (std::set<std::pair<unsigned, unsigned> >::iterator j = set2.begin(); j != set2.end(); ++j) {
235                                 unsigned d = opt_cache(i->first, i->second, j->first, j->second);
236                                 if (d < best_this_cost) {
237                                         best_this_cost = d;
238                                         best_set1 = i;
239                                 }
240                         }
241                 }
242
243                 set2.insert(*best_set1);
244                 set1.erase(best_set1);
245                 total_cost += best_this_cost;
246         }
247
248         return total_cost;
249 }
250 #endif
251
252 void print_tour(std::vector<std::pair<unsigned, unsigned> > &points)
253 {
254         std::set<std::pair<unsigned, unsigned> > points_left;
255         for (unsigned i = 0; i < points.size(); ++i) {
256                 points_left.insert(points[i]);
257         }
258         
259         for (unsigned i = 0; i < points.size(); ++i) {
260                 if (best_tour[i].side == 0)
261                         printf("%2u-%u (left side)  ", best_tour[i].row, best_tour[i].num);
262                 else
263                         printf("%2u-%u (right side) ", best_tour[i].row, best_tour[i].num);
264                 if (i == 0) {
265                         printf("           ");
266                 } else {
267                         printf("cost=%4u  ", best_tour[i].cost);
268                 }
269
270                 // let's see how good the MST heuristics are
271                 if (i != points.size() - 1) {
272                         std::set<std::pair<unsigned, unsigned> > mst_tree = points_left;
273                         printf("mst_bound=%5u, ", prim_mst(mst_tree));
274
275                         unsigned rest_cost = 0;
276                         for (unsigned j = i + 1; j < points.size(); ++j) {
277                                 rest_cost += best_tour[j].cost;
278                         }
279                         
280                         printf("rest_cost=%5u", rest_cost);
281                 }
282
283                 printf("\n");
284                 
285                 std::set<std::pair<unsigned, unsigned> >::iterator j = points_left.find(std::make_pair(best_tour[i].row, best_tour[i].num));
286                 points_left.erase(j);
287         }
288 }
289
290 unsigned do_tsp(std::vector<std::pair<unsigned, unsigned> > &points, std::set<std::pair<unsigned, unsigned> > &points_left, order *ord, order *temp, unsigned ind, unsigned cost_so_far)
291 {
292         if (cost_so_far >= best_so_far)
293                 return UINT_MAX;
294         if (ind == points.size()) {
295                 memcpy(best_tour, ord, sizeof(order) * points.size());
296                 printf("\nNew best tour found! cost=%u\n", cost_so_far);
297                 print_tour(points);
298                 best_so_far = cost_so_far;
299                 return 0;
300         }
301         
302         unsigned last_row = ord[ind-1].row;
303         unsigned last_switch = ord[ind-1].num;
304         unsigned last_side = ord[ind-1].side;
305
306         /* 
307          * The minimum spanning tree gives us a reliable lower bound for what we can
308          * achieve for the rest of the graph, so check it before doing anything else.
309          */
310         std::set<std::pair<unsigned, unsigned> > mst_set = points_left;
311         mst_set.insert(std::make_pair(last_row, last_switch));
312         
313         unsigned min_rest_cost = prim_mst(mst_set);
314         if (cost_so_far + min_rest_cost >= best_so_far) {
315                 return UINT_MAX;
316         }
317
318         /* 
319          * Simple heuristic: always search for the closest points from this one first; that
320          * will give us a sizable cutoff.
321          */
322         unsigned toi = 0;
323         
324         for (std::set<std::pair<unsigned, unsigned> >::iterator i = points_left.begin(); i != points_left.end(); ++i) {
325                 /* try both sides */
326                 temp[toi].row = i->first;
327                 temp[toi].num = i->second;
328                 temp[toi].side = 0;
329                 temp[toi].cost = cache(last_row, last_switch, last_side, i->first, i->second, 0);
330                 ++toi;
331
332                 temp[toi].row = i->first;
333                 temp[toi].num = i->second;
334                 temp[toi].side = 1;
335                 temp[toi].cost = cache(last_row, last_switch, last_side, i->first, i->second, 1);
336                 ++toi;
337         }
338         std::sort(temp, temp + toi);
339
340         unsigned best_this_cost = UINT_MAX;
341         for (unsigned i = 0; i < toi; ++i)
342         {
343                 ord[ind] = temp[i];
344                 
345                 std::set<std::pair<unsigned, unsigned> >::iterator j = points_left.find(std::make_pair(temp[i].row, temp[i].num));
346                 points_left.erase(j);
347                 unsigned cost_rest = do_tsp(points, points_left, ord, temp + points.size() * 2, ind + 1, cost_so_far + temp[i].cost);
348                 points_left.insert(std::make_pair(temp[i].row, temp[i].num));
349                 
350                 best_this_cost = std::min(best_this_cost, cost_rest);
351         }
352
353         return best_this_cost;
354 }
355
356 int main()
357 {
358         std::vector<std::pair<unsigned, unsigned> > points;
359         std::set<std::pair<unsigned, unsigned> > points_left;
360
361         for ( ;; ) {
362                 unsigned row, sw;
363                 if (scanf("%u-%u", &row, &sw) != 2)
364                         break;
365
366                 if (row < MIN_ROW || row > MAX_ROW || sw < MIN_SWITCH || sw > MAX_SWITCH) {
367                         fprintf(stderr, "%u-%u is out of bounds!\n", row, sw);
368                         exit(1);
369                 }
370
371                 points.push_back(std::make_pair(row, sw));
372                 if (points.size() != 1)
373                         points_left.insert(std::make_pair(row, sw));
374         }
375
376         // precalculate all distances
377         for (unsigned i = 0; i < points.size(); ++i) {
378                 for (unsigned j = 0; j < points.size(); ++j) {
379                         cache(points[i].first, points[i].second, 0, points[j].first, points[j].second, 0) =
380                                 distance(points[i].first, points[i].second, 0, points[j].first, points[j].second, 0);
381                         
382                         cache(points[i].first, points[i].second, 0, points[j].first, points[j].second, 1) =
383                                 distance(points[i].first, points[i].second, 0, points[j].first, points[j].second, 1);
384                         
385                         cache(points[i].first, points[i].second, 1, points[j].first, points[j].second, 0) =
386                                 distance(points[i].first, points[i].second, 1, points[j].first, points[j].second, 0);
387                         
388                         cache(points[i].first, points[i].second, 1, points[j].first, points[j].second, 1) =
389                                 distance(points[i].first, points[i].second, 1, points[j].first, points[j].second, 1);
390                         
391                         opt_cache(points[i].first, points[i].second, points[j].first, points[j].second) =
392                                 optimistic_distance(points[i].first, points[i].second, points[j].first, points[j].second);
393                         
394                         pess_cache(points[i].first, points[i].second, points[j].first, points[j].second) =
395                                 pessimistic_distance(points[i].first, points[i].second, points[j].first, points[j].second);
396                 }
397         }
398         
399         order *ord = new order[points.size()];
400         best_tour = new order[points.size()];
401         order *temp = new order[points.size() * points.size() * 4];
402         
403         /* always start at the first one, left side (hack) */
404         ord[0].row = points[0].first;
405         ord[0].num = points[0].second;
406         ord[0].side = 0;
407         
408         do_tsp(points, points_left, ord, temp, 1, 0);
409         printf("All done.\n");
410 }
411
412