POJ-2420 A Star not a Tree? 计算几何 模拟退火

POJ-2420 A Star not a Tree?

题意: 给定n个点, 找到一个点p. 使得p到所有点的距离之和最小.
分析: 模拟退火随机产生圆心坐标, 跑一遍模拟退火就行, 这题n的范围是100, 莫名其妙re, 开1000就ac了.
代码:

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
using namespace std;

const int MAXN = 1111;

const double eps = 1e-8;
const double pi = acos(-1);
const double inf = 0x3f3f3f3f;
struct Point {
  double x, y;
  Point() {}
  Point(double _x, double _y) {
    x = _x;
    y = _y;
  }
  double distance(Point b) { return hypot(x - b.x, y - b.y); }
};
Point p[MAXN];
int n;
Point ans;
double Rand() { return (double)rand() / RAND_MAX; }

double getdis(Point b) {
  double res = 0;
  for (int i = 0; i < n; i++) {
    res += b.distance(p[i]);
  }
  return res;
}
int main() {
  srand(0);
  while (scanf("%d", &n) != EOF) {
    ans.x = 0, ans.y = 0;
    for (int i = 0; i < n; i++) {
      scanf("%lf%lf", &p[i].x, &p[i].y);
      ans.x += p[i].x;
      ans.y += p[i].y;
    }
    ans.x /= n;
    ans.y /= n;
    double t = 100000;
    double res = getdis(ans);
    Point nxt;
    while (t > eps) {
      nxt.x = ans.x + t * (Rand() * 2 - 1);
      nxt.y = ans.y + t * (Rand() * 2 - 1);
      double dis = getdis(nxt);
      if (res > dis) {
        res = dis;
        ans = nxt;
      }
      t *= 0.97;
    }
    printf("%.0f", res);
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值