/* Compute TSP for the tree t -- use conquer for problems <= sz */ Tree tsp(Tree t,int sz,int nproc) { Tree left,right; Tree leftval; #ifdef FUTURES future_cell_pointer fc; #endif Tree rightval; int nproc_2 = nproc/2; if (t->sz <= sz) return conquer(t); left = t->left; right = t->right; #ifndef FUTURES leftval = tsp(left,sz,nproc_2); #else FUTURE(left,sz,nproc_2,tsp,&fc); #endif rightval = tsp(right,sz,nproc_2); #ifdef FUTURES leftval = (Tree) TOUCH(&fc); leftval = (Tree) fc.value; return merge(leftval,rightval,t,nproc); #else return merge(leftval,rightval,t,nproc); #endif }
// solves http://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=submit_problem&problemid=1437&category= int solve_beepers() { int T; cin >> T; for(int t = 0; t < T; ++t) { int N; cin >> N >> N; // throw away world size vector<tuple<int, int>> ps(1); cin >> get<0>(ps[0]) >> get<1>(ps[0]); cin >> N; ps.resize(1 + N); for(int n = 1; n <= N; ++n) cin >> get<0>(ps[n]) >> get<1>(ps[n]); //cout << "size = " << ps.size(); vvl g(ps.size(), vl(ps.size())); for(int v1 = 0; v1 < ps.size(); ++v1) for(int v2 = 0; v2 < ps.size(); ++v2) g[v1][v2] = abs(get<0>(ps[v1]) - get<0>(ps[v2])) + abs(get<1>(ps[v1]) - get<1>(ps[v2])); cout << "The shortest path has length " << tsp(g) << endl; } return 0; }
// executes the O(n^2 2^n) TSP DP // the subproblem is: "what is the minimum cost of starting // at node 0, ending at node t and visiting all nodes in // vis?" // g : the (not necessarily complete, not necessarily // symmetric) TSP instance // dp : a 2^n x n array for holding results // vis : a bitmask representing visited nodes // t : the last visited node // n : the number of nodes in the instance // returns: the cost of the minimum cycle through all nodes ll tsp(const vvl& g, vvl& dp, ll vis, int t, int n) { // -1 means not yet calculated if(dp[vis][t] == -1) { const ll pvis = vis & (~(1<<t)); // base case if(pvis == 0) { // -2 means invalid if(g[0][t] < 0) dp[vis][t] = -2; else dp[vis][t] = g[0][t]; } else { ll mi = -2; // could be impossible for(int s = 0; s < n; ++s) { // if we have visited s and // there is a path from s to t if((pvis & (1<<s)) != 0 && g[s][t] >= 0) { ll rec = tsp(g, dp, pvis, s, n); ll dist = rec + g[s][t]; if(rec >= 0 && (mi < 0 || mi > dist)) mi = dist; } } dp[vis][t] = mi; } } return dp[vis][t]; }
int main() { scanf("%d", &N); int allFlag = (1 << N) - 1; int m = 0x7fffffff; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { scanf("%d", &map[i][j]); } } memset(memory, 0, sizeof((memory))); /*for (int i = 0; i < N; i++) { int v = tsp(i, allFlag & ~(1 << i)); m = min(m, v); }*/ printf("%d", tsp(0, allFlag & ~(1 << 0))); return 0; }
static int tsp(int start, dataType set, tspPathAsmParamsType * data ) { dataType masked, mask; int result = -1, temp; int x; if (data->graph[(start*data->npow)+set] != -1) { return data->graph[(start*data->npow)+set]; } else { for ( x = 0; x < data->size; x++) { mask = data->npow - 1 - (dataType) pow(2, x); masked = set & mask; if (masked != set) { int tmp = tsp(x, masked,data); temp = data->inputData[(start*data->size)+x] + tmp; if (result == -1 || result > temp) { result = temp; data->path[(start*data->npow)+set] = x; } } } data->graph[(start*data->npow)+set] = result; return result; } }
void mc_main(void) { xprintf("[%02u]: mc_main\n", corenum()); hw_barrier(); if (corenum() == 2) { int path[NRTOWNS]; // current (partial) tour path int visited[NRTOWNS]; // count of tours of particular length int best_path[NRTOWNS];// current best tour path int min; // cost of best tour path // initialization min = 10000; for (unsigned int i = 0; i < NRTOWNS; i++) visited[i] = 0; path[0] = 0; // starting town, we are finidng a cycle so just choose town 0 xprintf("[%02u]: Starting TSP ...\n", corenum()); const unsigned int start_cycle = *cycleCounter; tsp(1, 0, path, visited, best_path, &min); // find a min cost tour const unsigned int end_cycle = *cycleCounter; // print results xprintf("[%02u]: computation time (in CPU cycles): %u\n", corenum(), end_cycle - start_cycle); xprintf("[%02u]: shortest path length is %d\n", corenum(), min); xprintf("[%02u]: best path found: ", corenum()); for (unsigned int i = 0; i < NRTOWNS; i++) printf("%d ", best_path[i]); xprintf("\n"); xprintf("level\tvisited\n"); for (unsigned int i = 0; i < NRTOWNS; i++) printf("%d\t%d\n",i,visited[i]); } }
// recursive TSP search: look for a town to visit, path[] contains // the len towns visited so far with a total (partial) // tour length of cost. void tsp(int len, int cost, int path[], int visited[], int best_path[], int *min) { const int me = path[len - 1]; // current end town // remember how many times we saw a tour of this length visited[len - 1]++; if (len == NRTOWNS) { const int new_cost = cost + distance[me][path[0]]; if (new_cost < *min) { // new min cost tour, remember cost and path *min = new_cost; for (unsigned int i = 0; i < NRTOWNS; i++) best_path[i] = path[i]; } } else { // look for next town in tour for (unsigned int i = 0; i < NRTOWNS; i++) { const int new_cost = cost + distance[me][i]; if (!present(i, len, path) & (new_cost < *min)) { path[len] = i; tsp(len + 1, new_cost, path, visited, best_path, min); } } } }
int tsp(int node, int mask) { // @param: mask - tracks visited Cities if(dp[node][mask] != INFN) return dp[node][mask]; int best = INFN; // Best Price bool temp = false; if(mask == 0 && node == names.at(city)) { // Valid Path: Terminates at Toronto done = temp = true; best = 0; } for(auto& next: graph[node]) { int node_next = next.first; int node_cost = next.second; if((mask >> node_next) & 1) // Bit is SET: Unvisited { done = false; int mask_next = mask & ~(1 << node_next); // Turns Bit OFF: Visited int fare = tsp(node_next, mask_next) + node_cost; if(fare < best) { // Better Price best = fare; if(done) // Records valid path child[node] = node_next; temp = done; } done = false; } } done = temp; // Currently Selected (Cheapest) Path is Valid return dp[node][mask] = best; }
// solves example from http://en.wikipedia.org/wiki/Held%E2%80%93Karp_algorithm // optimal result = 21 int test() { vvl g = {{ 0, 2, 9, 10}, { 1, 0, 6, 4}, {15, 7, 0, 8}, { 6, 3, 12, 0}}; cout << tsp(g) << endl; return 0; }
void CCandleChart::OnBnClickedRightButton() { if ((tEnd.GetHour() == 15) && (tEnd.GetMinute() == 15)) return; COleDateTimeSpan tsp(0, 0, 15, 0); tBegin += tsp; tEnd += tsp; pPriceDateAxis->SetMinMax(tBegin, tEnd); pVolumeDateAxis->SetMinMax(tBegin, tEnd); pAxis->SetAutomatic(true); // TODO: 在此添加控件通知处理程序代码 }
int main(int argc, char *argv[]) { int i; init(); tsp(); printf("The best route is:"); for (i = 0; i < N; i++) printf("%d ", result[i]); printf("\ntest = %d\n", test); return 0; }
int tsp(int pos, int bitmask){ int nxt; if(bitmask == (1 << (n + 1)) - 1) return dist[pos][0]; if(memo[pos][bitmask] != -1) return memo[pos][bitmask]; int ans = 2000000000; for(nxt = 0; nxt <= n; nxt++) if(nxt != pos && !(bitmask & (1 << nxt))) ans = min(ans, dist[pos][nxt] + tsp(nxt, bitmask | (1 << nxt))); return memo[pos][bitmask] = ans; }
void tsp (int hops, int len, uint64_t vpres, tsp_path_t path, long long int *cuts, tsp_path_t sol, int *sol_len) { if (len + cutprefix[(nb_towns-hops)] >= minimum) { (*cuts)++ ; return; } /* calcul de l'arbre couvrant comme borne inférieure */ if ((nb_towns - hops) > 6 && lower_bound_using_hk(path, hops, len, vpres) >= minimum) { (*cuts)++; return; } /* un rayon de coupure à 15, pour ne pas lancer la programmation linéaire pour les petits arbres, plus rapide à calculer sans */ if ((nb_towns - hops) > 22 && lower_bound_using_lp(path, hops, len, vpres) >= minimum) { (*cuts)++; return; } if (hops == nb_towns) { int me = path [hops - 1]; int dist = tsp_distance[me][0]; // retourner en 0 if ( len + dist < minimum ) { pthread_mutex_lock(&minimum_mutex); if ( len + dist < minimum ) { minimum = len + dist; *sol_len = len + dist; memcpy(sol, path, nb_towns*sizeof(int)); if (!quiet) print_solution (path, len+dist); } pthread_mutex_unlock(&minimum_mutex); } } else { int me = path [hops - 1]; for (int i = 0; i < nb_towns; i++) { if (!present (i, hops, path, vpres)) { path[hops] = i; vpres |= (1<<i); int dist = tsp_distance[me][i]; tsp (hops + 1, len + dist, vpres, path, cuts, sol, sol_len); vpres &= (~(1<<i)); } } } }
void tsp(int city) { int ncity; visited[city] = 1; printf("%d ->",city); ncity = least(city); if(ncity == 999) { cost += a[city][1]; printf("1\n"); return; } tsp(ncity); }
int main() { std::ifstream data("points.dat", std::ifstream::in); route Tsp; point aux; while( data >> aux.real() >> aux.imag()) { Tsp.push_back(aux); } std::cout << tsp(&Tsp) << std::endl; return 0; }
int main(){ scanf("%d", &TC); while (TC--){ scanf("%d %d", &xsize, &ysize); scanf("%d %d", &x[0], &y[0]); scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d %d", &x[i], &y[i]); for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) dist[i][j] = abs(x[i] - x[j]) + abs(y[i] - y[j]); memset(memo, -1, sizeof memo); printf("The shortest path has length %d\n", tsp(0, 1)); } return 0; }
void *main_tsp(void *arg){ unsigned long long perf; struct timespec t1, t2; uint64_t vpres=0; long long int myCuts = 0; clock_gettime (CLOCK_REALTIME, &t1); /* calculer chacun des travaux */ tsp_path_t solution; memset (solution, -1, MAX_TOWNS * sizeof (int)); solution[0] = 0; pthread_mutex_lock(&q_mutex); while (!empty_queue (&q, &q_mutex)) { int hops = 0, len = 0; get_job (&q, solution, &hops, &len, &vpres, &q_mutex); pthread_mutex_unlock(&q_mutex); //printf("Thread %ld\n", syscall(SYS_gettid)); // le noeud est moins bon que la solution courante if (minimum < INT_MAX && (nb_towns - hops) > 10 && ( (lower_bound_using_hk(solution, hops, len, vpres)) >= minimum || (lower_bound_using_lp(solution, hops, len, vpres)) >= minimum)){ pthread_mutex_lock(&q_mutex); continue; } tsp (hops, len, vpres, solution, &myCuts, sol, &sol_len); pthread_mutex_lock(&q_mutex); } pthread_mutex_unlock(&q_mutex); /* update cuts */ pthread_mutex_lock(&cuts_mutex); cuts += myCuts; pthread_mutex_unlock(&cuts_mutex); clock_gettime (CLOCK_REALTIME, &t2); perf = TIME_DIFF (t1,t2); printf("Son thread %ld finished after %lld.%03lld ms\n\n", syscall(SYS_gettid), perf/1000000ll, perf%1000000ll); return 0 ; }
int main (int argn, char* args[]) { int nVertices, nEdges=0, nMax=0, i, j, k=0; // Demande du nombre de sommets du graphe printf("Enter the number of patients to visit : "); scanf("%d", &nVertices); // Création du graphe sous forme de matrice d'adjacence et initialisation des poids à -1 vector<vector<int> > G(nVertices); for(i=0; i < nVertices ; i++) G[i].resize(nVertices,-1); // Saisie du graphe for(i = 0 ; i < nVertices ; i++) { for(j = i + 1 ; j < nVertices ; j++) { printf("\nEnter the length of the path between [%d] and [%d] : ",i,j); scanf("%d",&k); G[i][j] = k; G[j][i] = k; nEdges++; } } // Affichage du graphe printf("\nNumber of Edges : %d\n\n",nEdges); printGraph(G); // Demande du point de départ du chemin k=0; printf("Enter the first patient to visit : "); scanf("%d",&k); // Création du chemin vector<int> path = tsp(G,k); // Affichage du chemin printf("Itinerary : "); for(i = 0 ; i < path.size() ; i++) printf("%d ", path[i]); return 0; }
int main() { matrix<std::size_t> mat(5); std::array<std::array<std::size_t, 5>, 5> arr = {{ {{ 0, 14, 4, 10, 20 }}, {{ 14, 0, 7, 8, 7 }}, {{ 4, 5, 0, 7, 16 }}, {{ 11, 7, 9, 0, 2 }}, {{ 18, 7, 17, 4, 0 }} }}; for (std::size_t i = 0; i < 5; ++i) { for (std::size_t j = 0; j < 5; ++j) { mat(i, j) = arr[i][j]; } } auto path = tsp(mat); for (auto && elem : path) { std::cout << elem + 1 << " "; } std::size_t cost = 0; for (std::size_t i = 0; i < mat.size() - 1; ++i) { cost += mat(path[i], path[i + 1]); } cost += mat(path.back(), path.front()); std::cout << "\n" << cost; //----------- std::vector<size_t> another = { 0, 3, 4, 1, 2 }; cost = 0; for (std::size_t i = 0; i < mat.size() - 1; ++i) { cost += mat(another[i], another[i + 1]); } cost += mat(another.back(), another.front()); std::cout << "\n" << cost; }
void tsp (int hops, int len, Path_t path, int *cuts) { int i ; int me, dist ; if (len >= minimum) { #ifdef DEBUG printf ("Too long path, len = %3d: ", len) ; for (i=0; i < hops; i++) printf ("%2d ", path[i]) ; printf ("\n") ; #endif (*cuts)++ ; return; } if (hops == NbCities) { if (len < minimum) { minimum = len ; printf ("found path len = %3d :", len) ; for (i=0; i < NbCities; i++) printf ("%2d ", path[i]) ; printf ("\n") ; } } else { me = path [hops-1] ; printf("hop:%d me:%d len:%d minimum:%d pPath:%p\n",hops,me,len,minimum,path); for (i=0; i < NbCities; i++) { if (!present (i, hops, path)) { path [hops] = i ; dist = distance[me][i] ; tsp (hops+1, len+dist, path, cuts) ; } } } }
void tsp (int hops, int len, Path_t path, int *cuts) { int i ; int me, dist ; if (len >= minimum) { #ifdef DEBUG PrintPath("Too long path : ", hops, path); #endif (*cuts)++ ; return; } if (hops == NbCities) { #pragma omp critical if (len < minimum) { minimum = len ; // printf ("found path len = %3d :", len) ; // for (i=0; i < NbCities; i++) // printf ("%2d ", path[i]) ; // printf ("\n") ; } } else { me = path [hops-1] ; for (i=0; i < NbCities; i++) { if (!present (i, hops, path)) { path [hops] = i ; dist = distance[me][i] ; tsp (hops+1, len+dist, path, cuts) ; } } } }
void wrap(Signal *s) { if(s->alg == 0) s->alg = defroute; switch(s->alg) { case RTSP: tsp(s); s->prfn = prseq; break; case RTSPE: tspe(s); s->prfn = prseq; break; case RHAND: hand(s); s->prfn = prseq; break; case RMST: mst(s); s->prfn = prmst; break; case RMST3: mst3(s); s->prfn = prmst; break; default: f_major("Unknown routing algorithm %d", s->alg); abort(); return; } calclen(s); }
void * tsp_worker(void * args) { WorkerArgs * a = (WorkerArgs*) args; long long int cuts; while (!empty_queue(a->q)) { int hops = 0, len = 0; cuts = 0; pthread_mutex_lock(&mutex_queue); get_job(a->q, a->solution, &hops, &len); pthread_mutex_unlock(&mutex_queue); tsp(hops, len, a->solution, &cuts, a->sol, a->sol_len); pthread_mutex_lock(&mutex_cuts); *(a->cuts) += cuts; pthread_mutex_unlock(&mutex_cuts); } free(args); return (void*)42; }
void tsp() { int i, j; for (i = 0; i < COUNT_P; i++) { printf("get_dist(p[%d]) = %lf\n", i, get_dist(p[i])); if (get_dist(p[i]) < best_dist) { for (j = 0; j < N; j++) { result[j] = p[i][j]; } map(p[i]); test++; break; } } if (i < COUNT_P) tsp(); else { return; } }
int main() { freopen("input.in", "r", stdin); freopen("output.out", "w", stdout); scanf(" %d%d", &N, &M); // Nodes, Edges for(int i = 0; i < N; ++i) { // Read Cities scanf(" %s", buff[i]); tem[0] = buff[i]; names[tem[0]] = i; } for(int i = 0; i < M; ++i) { // Adjacency List int u, v, w; scanf(" %s%s%d", &buff[N], &buff[N+1], &w); tem[0] = buff[N]; tem[1] = buff[N+1]; u = names.at(tem[0]); v = names.at(tem[1]); graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } // Initialize 'dp' to Infinity memset(dp, 0x7F, sizeof(dp)); scanf(" %s", &buff[N]); city = buff[N]; // Start / Final City int node = names.at(city); int mask = (1 << N) - 1; // In Binary: 11...11 tsp(node, mask); // Runs TSP do { // Outputs Edges in Path printf("%s -> %s ", buff[node], buff[child[node]]); for(auto& next: graph[node]) if(next.first == child[node]) printf("[$%d]\n", next.second); node = child[node]; } while(node != names.at(city)); printf("The optimal journey costs $%d.\n", dp[names.at(city)][mask]); return 0; }
int main(int argc, char *argv[]) { int i, j; printf("Enter the No of Cities\n"); scanf("%d", &no); printf("\nEnter the Adjacency Matrix\n"); for(i = 1; i <= no; i++) for(j = 1; j <=no; j++) scanf("%d", &a[i][j]); printf("Using Dynamic Prog\n"); tsp(1); printf("Cost is %d\n", cost); printf("Using approx method\n"); nearest_n(1); printf("Cost is %d\n", sum); printf ("\nRatio is %f\n", (float)sum/cost); return 0; }
int main(int argc,char *argv[]) { Tree t; int num; num=dealwithargs(argc,argv); chatting("Building tree of size %d\n",num); t=build_tree(num,0,0,NumNodes,0.0,1.0,0.0,1.0); if (!flag) chatting("Past build\n"); if (flag) chatting("newgraph\n"); if (flag) chatting("newcurve pts\n"); printf("Call tsp(t, %d, %d)\n", conquer_thresold, NumNodes); tsp(t,conquer_thresold, NumNodes); if (flag) print_list(t); if (flag) chatting("linetype solid\n"); return 0; }
int tsp(int from, int toFlag) { int &memo = memory[from][toFlag]; if (memo != 0) return memo; if (bitcount(toFlag) == 1) { int to = getIndex(toFlag); return map[from][to]; } memo = 0x7fffffff; for (int i = 0; i < N; i++) { if (!(toFlag & (1 << i))) continue; int v = map[from][i] + tsp(i, (toFlag & ~(1 << i))); memo = min(memo, v); } return memo; }
void tsp (int hops, int len, Path_t path, int *cuts) { int i ; int me, dist ; if (len >= minimum) { cuts[hops]++ ; return; } if (hops == NrTowns) { if (len + distance[0][path[NrTowns-1]] < minimum) { minimum = len + distance[0][path[NrTowns-1]] ; fprintf (stderr, "found path len = %3d :", minimum) ; for (i=0; i < NrTowns; i++) fprintf (stderr, "%2d ", path[i]) ; fprintf (stderr, "\n") ; //printPath(path); } } else { me = path [hops-1] ; for (i=0; i < NrTowns; i++) { if (!present (i, hops, path)) { path [hops] = i ; dist = distance[me][i] ; tsp (hops+1, len+dist, path, cuts) ; } } } }
int main (int argc, char **argv) { unsigned long temps; int i; Path_t path; int cuts = 0; struct timeval t1, t2; if (argc != 3) { fprintf (stderr, "Usage: %s <nbcities ( MAXNBCITIES = %d )> <seed> \n", argv[0], MAXNBCITIES) ; exit (1) ; } NbCities = atoi (argv[1]) ; seed = atoi(argv[2]); minimum = INT_MAX ; printf ("NbCities = %3d\n", NbCities) ; genmap () ; gettimeofday(&t1, NULL); for(i = 0; i < MAXNBCITIES; i++) path[i] = -1 ; /* Ville de d�part : Ville 0 */ path [0] = 0; tsp(1, 0, path, &cuts); gettimeofday(&t2, NULL); temps = TIME_DIFF(t1,t2); printf("minimum = %d time = %ld.%03ldms (%d coupures)\n", minimum, temps/1000, temps%1000, cuts); return 0 ; }