UVa 216 - Getting in Line(回溯法)

题目链接:UVa 216 - Getting in Line

挺简单的一道回溯题,可是我做了好久啊啊啊啊啊啊啊。还是不熟练啊啊啊啊啊。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <stdio.h>
#include <cstring>

//#define test

using namespace std;

const int MAX_N = 8 + 2;
int vis[MAX_N];
int step[MAX_N];
int final_step[MAX_N];
int point[MAX_N][2];
int n;
double _min;

double disAll()
{
    double sum = 0.0;
    for(int i = 0;i < n - 1;i++)
        sum += sqrt(pow(point[step[i]][0] - point[step[i+1]][0],2) + pow(point[step[i]][1] - point[step[i+1]][1],2));
    sum += (n - 1 ) * 16;
    return sum;
}
double disTwo(int i)
{
    return sqrt(pow(point[final_step[i]][0] - point[final_step[i+1]][0],2) + pow(point[final_step[i]][1] - point[final_step[i+1]][1],2)) + 16;
}
void dfs(int cur)
{
    if(cur == n)
    {
        double temp = disAll();
        //_min = _min < temp ? _min : temp;
        if(_min > temp)
        {
            _min = temp;
            memcpy(final_step,step,sizeof(step));
        }
    }
    else
    {
        for(int i = 0;i < n;i++)
        {
            if(vis[i])
                continue;
            step[cur] = i;
            vis[i] = 1;
            dfs(cur+1);
            vis[i] = 0;
        }
    }
}
int main()
{
#ifdef test
    freopen("in.txt","r",stdin);
#endif // test
    int T = 1;
    while(cin>>n,n)
    {
        _min = 1000000;
        int i;
        for(i = 0;i < n;i++)
            cin>>point[i][0]>>point[i][1];
        dfs(0);
        cout<<"**********************************************************"<<endl;
        cout<<"Network #"<<T++<<endl;
        for(i = 0;i < n - 1;i++)
        {
            cout<<"Cable requirement to connect ("<<point[final_step[i]][0]<<","<<point[final_step[i]][1]<<") to ("<<point[final_step[i+1]][0]<<","<<point[final_step[i+1]][1]<<") is ";
            cout<<fixed<<setprecision(2)<<disTwo(i);
            cout<<" feet."<<endl;
        }
        cout<<"Number of feet of cable required is ";
        cout<<fixed<<setprecision(2)<<_min;
        cout<<"."<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值