uva 216 Getting in Line

这是一道有意思的题,当然一开始看,感觉挺复杂的,后来用了algoritnm中的next_permutation一下子简单化了

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
struct point
{
    double x,y;
};

struct Dis
{
    point a,b;
    double dis;
};

double diss(point a,point b)
{
    return  sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) + 16;
}

int main()
{
    point po[10];
    Dis ansdis[10],zdis[10];
    int n,i,j,t = 0,a[10];
    double MIN,sum;
    while(~scanf("%d",&n))
    {
        if(n == 0) break;
        MIN = 1<<30;
        for(i = 0; i < n; i ++)
        {
            scanf("%lf %lf",&po[i].x,&po[i].y);
            a[i] = i;
        }
        do
        {
            for(i = 0,j =0,sum = 0; i < n-1; i++,j ++)
            {
                zdis[j].a = po[a[i]];
                zdis[j].b = po[a[i+1]];
                zdis[j].dis = diss(po[a[i]],po[a[i+1]]);
                sum += zdis[j].dis;
            }
            if(sum < MIN)
            {
                MIN = sum;
                for(i = 0; i < n-1; i ++)
                {
                    ansdis[i].a = zdis[i].a;
                    ansdis[i].b = zdis[i].b;
                    ansdis[i].dis = zdis[i].dis;
                }
            }
        }
        while(next_permutation(a,a+n));
        printf("**********************************************************\n");
        printf("Network #%d\n",++t);
        for(i = 0; i < n -1; i++)
        {
            printf("Cable requirement to connect (%.0lf,%.0lf) to (%.0lf,%.0lf) is %.2lf feet.\n",ansdis[i].a.x,ansdis[i].a.y,ansdis[i].b.x,ansdis[i].b.y,ansdis[i].dis);
        }
        printf("Number of feet of cable required is %.2lf.\n",MIN);
    }
    return 0;
}


你可能感兴趣的:(uva 216 Getting in Line)