POJ 2420 A Star not a Tree? (模拟退火)

题意:给出平面坐标内的一些点,要求你在坐标平面内找到一点使所有点到该点的距离和最小,输出这个距离

分析:模拟退火,在误差范围内找到近似答案


#include<cstring>
#include<string>
#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstdlib>
#include<cmath>
#include<vector>
//#pragma comment(linker, "/STACK:1024000000,1024000000");

using namespace std;

#define INF 0x3f3f3f3f
#define eps 1e-5
#define delte 0.98

struct node
{
    double x,y;
} p[105];


int n;
int dir[][5]= {{0,1},{0,-1},{1,0},{-1,0}};

double dis(node a,node b)
{
    return sqrt( (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y) );
}

double getsum(node k)
{
    double ans=0;
    for(int i=0; i<n; i++)
    {
        ans+=dis(k,p[i]);
    }
    return ans;
}

double solve()
{
    node temp;
    temp.x=temp.y=0;
    double ans=getsum(temp);
    double t=100;
    while(t>eps)
    {
        int flag=1;
        while(flag)
        {
            flag=0;
            for(int i=0; i<4; i++)
            {
                node k=temp;
                k.x+=dir[i][0]*t;
                k.y+=dir[i][1]*t;
                double len=getsum(k);
                if(len<ans)
                {
                    ans=len;
                    temp=k;
                    flag=1;
                }
            }
        }
        t*=delte;
    }
    return ans;
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0; i<n; i++)
        {
            scanf("%lf%lf",&p[i].x,&p[i].y);
        }
        double ans=solve();
        printf("%.0f\n",ans);
    }
}


你可能感兴趣的:(POJ 2420 A Star not a Tree? (模拟退火))