#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#define N 1005
#define eps 1e-8
#define INF 1e99
#define delta 0.98
#define T 100
using namespace std;
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { -1, 1, 0, 0 };
struct Point
{
int x;
int y;
};
Point p[N];
double dist(Point A, Point B)
{
return sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y));
}
double getsum(Point p[], int n, Point t)
{
double ans = 0;
while (n--)
{
ans += dist(p[n], t);
}
return ans;
}
double search(Point p[], int n)
{
Point s = p[0];
double t = T;
double ans = INF;
while (t > eps)
{
bool flag = 1;
while (flag)//在每个t那找到一个最优的点 ,然后退出更新下一个t进行搜索
{
flag = 0;
for (int i = 0; i < 4; i++)
{
Point z;
z.x = s.x + dx[i] * t;
z.y = s.y + dy[i] * t;
double tp = getsum(p, n, z);
if (ans>tp)
{
ans = tp;
s = z;
flag = 1;
}
}
}
t = t*delta;
}
return ans;
}
int main()
{
int n;
while (scanf("%d",&n )!= EOF)
{
for (int i = 0; i < n; i++)
{
cin >> p[i].x >> p[i].y;
}
cout << search(p, n);
}
return 0;
}
退火算法求解费马点
最新推荐文章于 2024-03-10 09:20:18 发布