UVa 216 - Getting in Line
2014-05-20 23:06
357 查看
暴力回溯
这么一看回溯题其实没那么难啊
题意是:
给出n 个点的坐标,要求把n个点连成一条线,使这条线长度最短
因为n最大为8
暴力的时间复杂度是O(8!)不会超时
依次枚举即可
代码如下:
这么一看回溯题其实没那么难啊
题意是:
给出n 个点的坐标,要求把n个点连成一条线,使这条线长度最短
因为n最大为8
暴力的时间复杂度是O(8!)不会超时
依次枚举即可
代码如下:
#include <cmath> #include <cstdio> #include <iostream> #include <algorithm> #define MAXN 10 #define ll long long using namespace std; struct Point { int x, y; }a[MAXN], net[MAXN], cp[MAXN]; double dis, bestdis; int tot, n; void find(int cur) { if(cur > n) { tot++; /* for(int i=1; i<=n; ++i) cout << net[i].x << " " << net[i].y << "\t" << sqrt(pow(net[i].x-net[i-1].x, 0.5) + pow(net[i].y-net[i-1].y, 0.5)) << endl; */ if(dis < bestdis) { bestdis = dis; for(int i=1; i<=n; ++i) { cp[i].x = net[i].x; cp[i].y = net[i].y; } } } else { for(int i=1; i<=n; ++i) { net[cur].x = a[i].x; net[cur].y = a[i].y; int ok = 1; for(int j=1; j<cur; ++j) { if(net[j].x==net[cur].x && net[j].y==net[cur].y) { ok = 0; break; } } double temp; if(ok) { if(cur != 1) temp = sqrt(pow(net[cur].x-net[cur-1].x, 2.0) + pow(net[cur].y-net[cur-1].y, 2.0)); else temp = 0; dis += temp; find(cur+1); dis -= temp; } } } } int main(void) { int T = 1; while(cin >> n, n) { for(int i=1; i<=n; ++i) { cin >> a[i].x >> a[i].y; } cout << "**********************************************************" << endl; cout << "Network #" << T++ << endl; tot = 0; dis = 0; bestdis = 1e10; net[0].x = 0; net[0].y = 0; find(1); double temp; for(int i=1; i<n; ++i) { temp = sqrt(pow(cp[i+1].x-cp[i].x, 2.0) + pow(cp[i+1].y-cp[i].y, 2.0)); printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n", cp[i].x, cp[i].y, cp[i+1].x, cp[i+1].y, temp+16.0); } printf("Number of feet of cable required is %.2lf.\n", bestdis+(n-1)*16.0); } return 0; }
相关文章推荐
- uva216 Getting in Line
- UVA 216 Getting in Line
- UVA216 Getting in Line
- uva 216 - Getting in Line
- UVa 216 - Getting in Line
- UVA 216 Getting in Line dfs
- UVA216-Getting in Line
- Getting in Line UVA 216
- uva 216 - Getting in Line 带宽
- uva-216 - Getting in Line
- uva - 216 - Getting in Line
- UVA_216_Getting in Line_brute_force
- UVa 216 Getting in Line【枚举排列】
- UVA - 216 Getting in Line
- UVa 216 Getting in Line
- UVA - 216 Getting in Line (全排列枚举 和 回溯两种解法)
- UVA 216(Getting in Line)回溯
- uva 216 - Getting in Line
- UVA 216 Getting in Line
- UVa 216 - Getting in Line