您的位置:首页 > 其它

UVa 216 Getting in Line

2014-03-18 19:08 295 查看
入门经典里推荐的有关暴力求解的题目,正好新学了STL里有一个算法生成下一个排列。

题目里点最多8个,排列量最大8!,只有4万多,暴力求解可行,第一次在UVa上做题,,努力。

#include<cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct Points
{
double x,y,dis;
}a[10],res[10];//a用来输入,res保存结果
double getdis(Points &a, Points &b)//计算距离
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y))+16;
}
int main()
{
int n,k=1;
while(~scanf("%d",&n) && n)
{
printf("**********************************************************\n");
printf("Network #%d\n",k++);
int i,data[10];
double Min=2147483645,resd[10];
for(i=0;i<n;i++)
{
scanf("%lf%lf",&a[i].x,&a[i].y);
data[i]=i;        //记录每个点的索引
}
do{
double sum=0,tmpdis[10];
for(i=0;i<n-1;i++)
{
tmpdis[i]=getdis(a[data[i]],a[data[i+1]]);
sum+=tmpdis[i];
}
if(sum<Min)   // 如果找到更小的距离,保存点坐标与点间距
{
for(int j=0;j<n-1;j++)
{
resd[j]=tmpdis[j];
res[j]=a[data[j]];
}
res[n-1]=a[data[n-1]];
Min=sum;
}
}while (next_permutation(data,data+n));//下一个排列
for(i=0;i<n-1;i++)
printf("Cable requirement to connect (%.lf,%.lf) to (%.lf,%.lf) is %.2lf feet.\n",res[i].x,res[i].y,res[i+1].x,res[i+1].y,resd[i]);
printf("Number of feet of cable required is %.2lf.\n",Min);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: