HDU 3548 Enumerate the Triangles(找周长最小的三角形)

来源:互联网 发布:xp怎么安装网络打印机 编辑:程序博客网 时间:2024/06/05 23:57

题目链接:Click here~~

题意:

平面上有n(n<=1000)点,问组成的三角形中,周长最小是多少。

解题思路:

如果直接枚举的话,是O(n^3)肯定会超时,所以要优化。

首先我们考虑,周长c=L1+L2+L3,所以推得c > 2Li,假设Li的端点为点a、b,则又有Li>=| Xa-Xb |,故c > 2*| Xa-Xb |。

可以先按照X坐标从小到大排序,然后当已得到的最小值ans <= 2*|Xa-Xb|的时候,break。

#include <math.h>#include <stdio.h>#include <algorithm>using namespace std;#define min(a,b) a < b ? a : bstruct TT{    int x,y;    bool operator <(const TT& s)const    {        return x < s.x;    }}A[1002];bool One_Line(const TT& s1,const TT& s2,const TT& s3){    return (s2.y-s1.y)*(s3.x-s2.x) == (s3.y-s2.y)*(s2.x-s1.x);}double dis(const TT& s1,const TT& s2){    return sqrt( (double)(s1.x-s2.x)*(s1.x-s2.x) + (s1.y-s2.y)*(s1.y-s2.y) );}int main(){    int z,n,ncase=0;    scanf("%d",&z);    while(z--)    {        scanf("%d",&n);        for(int i=0;i<n;i++)            scanf("%d%d",&A[i].x,&A[i].y);        sort(A,A+n);        double ans = 1e7;        for(int i=0;i<n-2;i++)        {            for(int j=i+1;j<n-1;j++)            {                if(ans <= 2*(A[j].x-A[i].x))                    break;                double a = dis(A[i],A[j]);                if(ans <= 2*a)                    continue;                for(int k=j+1;k<n;k++)                {                    if(ans <= 2*(A[k].x-A[i].x))                        break;                    if(One_Line(A[i],A[j],A[k]))                        continue;                    double b = dis(A[j],A[k]);                    double c = dis(A[k],A[i]);                    ans = min(ans,a+b+c);                }            }        }        printf("Case %d: ",++ncase);        if(ans == 1e7)            puts("No Solution");        else            printf("%.3f\n",ans);    }    return 0;}


原创粉丝点击