旅行商问题(tsp)之分支定界法
http://soj.sysu.edu.cn/show_problem.php?pid=1001&cid=1816
做了一个晚上的题,真是弱爆了...
其实就是深搜最短路,不过加了一个upper bound用来剪枝,因为数据比较小可以过!
深搜还是要熟悉啊!
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 double graph[25][25]; 6 int vis[25]; 7 double a[25]; 8 double ub; 9 double ans; 10 11 12 struct point { 13 int x; 14 int y; 15 }p[25]; 16 17 double dis(point a, point b) 18 { 19 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 20 } 21 22 void dfs(int n, int x, double temp, int cnt) 23 { 24 // printf("%.2lf\n", temp); 25 if(cnt == n-2) 26 { 27 ub = min(ub, temp+graph[x][n-1]); 28 return ; 29 } 30 vis[x]=1; 31 for(int i=0; i<n-1; i++) 32 { 33 if(graph[x][i] && !vis[i]) 34 { 35 temp += graph[x][i]; 36 if(temp < ub) 37 dfs(n, i, temp, cnt+1); 38 temp -= graph[x][i]; 39 vis[i]=0; 40 41 } 42 } 43 44 45 } 46 47 48 int main() 49 { 50 int t, n, x, y; 51 scanf("%d", &t); 52 while(t--) 53 { 54 int cnt=0; 55 ub=0x3f3f3f3f; 56 double temp=0; 57 memset(graph, 0, sizeof(graph)); 58 memset(vis, 0, sizeof(vis)); 59 60 scanf("%d", &n); 61 for(int i=0; i<n; i++) 62 scanf("%d%d", &p[i].x, &p[i].y); 63 64 for(int i=0; i<n; i++) 65 for(int j=0; j<n; j++) 66 graph[i][j] = dis(p[i], p[j]); 67 68 vis[0]=1; 69 dfs(n,0,temp,0); 70 printf("%.2lf\n", ub); 71 } 72 return 0; 73 }