Cycle greedIt(const Matrix &mat) { size_t n = mat.size(); Cycle cycle; vector<bool> visited(n, false); visited[0] = true; int i = 0; while (cycle.size() != n) { int best_j = 0; int best_val = INT32_MAX; for (int j = 0; j < n; j++) { if (visited[j] || best_val < mat[i][j]) continue; best_j = j; best_val = mat[i][j]; } cycle.push_back(best_j); visited[best_j] = true; i = best_j; } cycle.push_front(0); return cycle; }
Cycle twoOptAllowNeg(const Matrix &mat, Cycle cycle, int default_neg, int diff_d, int min) { size_t cycle_size = cycle.size(); int improve = 0; bool distance_treshold = false; while (improve < 10) { int neg_imp = default_neg; int best_distance = countCycle(mat, cycle); for (int i = 1; i < cycle_size - 1; i++) { for (int j = i + 1; j < cycle_size - 1; j++) { Cycle new_cycle = swapCities(cycle, i, j); int new_distance = countCycle(mat, new_cycle); int diff_distance = new_distance - best_distance; if (distance_treshold) { if ((new_distance < min) && (new_distance < best_distance)) { improve = 0; neg_imp--; cycle = new_cycle; best_distance = new_distance; } } else { if (new_distance < best_distance || (diff_distance < diff_d && neg_imp > 0)) { improve = 0; neg_imp--; cycle = new_cycle; best_distance = new_distance; if (new_distance < min) distance_treshold = true; } } } } improve++; } return cycle; }
Cycle swapCities(const Cycle &cycle, const int &a, const int &b) { Cycle n_cycle; size_t cycle_size = cycle.size(); Cycle::const_iterator it; vector<int> vcycle; for (const auto &c : cycle) vcycle.push_back(c); for ( int c = 0; c <= a - 1; ++c ) n_cycle.push_back(vcycle[c]); for (int c = a, dec = 0; c <= b; ++c, dec++) n_cycle.push_back(vcycle[b - dec]); for ( int c = b + 1; c < cycle_size; ++c ) n_cycle.push_back(vcycle[c]); return n_cycle; }
bool cycle_cmp_bool(const Cycle & a, const Cycle & b) { return a.size() < b.size(); }