UVa 216 - Getting in Line

暴力回溯大笑

这么一看回溯题其实没那么难啊

题意是:

给出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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值