模拟退火算法(星星还是树)

本文介绍了一道关于二维空间中寻找距离之和最小点的问题,通过模拟退火算法实现求解。博主展示了如何利用随机搜索和温度衰减策略来找到最优解,适合理解动态规划和优化算法在实际问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://www.acwing.com/problem/content/description/3170/

在二维平面上有 n 个点,第 i 个点的坐标为 (xi,yi)。

请你找出一个点,使得该点到这 n 个点的距离之和最小。

该点可以选择在平面中的任意位置,甚至与这 n 个点的位置重合。

输入格式
第一行包含一个整数 n。

接下来 n 行,每行包含两个整数 xi,yi,表示其中一个点的位置坐标。

输出格式
输出最小距离和,答案四舍五入取整。

数据范围
1≤n≤100,
0≤xi,yi≤10000
输入样例:

4
0 0
0 10000
10000 10000
10000 0

输出样例:

28284

代码
#include<stdio.h>
#include<cmath>
#include<ctime>
#include<iostream>
#include<algorithm>
using namespace std;
#define fi first
#define se second

int n;
double ans;
typedef pair<double, double> point;
point a[105];

double rand(double l, double r)
{
	return (double)rand() / RAND_MAX * (r - l) + l;
}

double dis(point x, point y)
{
	double dx = x.fi - y.fi;
	double dy = x.se - y.se;
	return sqrt(dx * dx + dy * dy);
}

double cal(point x)
{
	double res = 0;
	for(int i=1;i<=n;i++) res += dis(x, a[i]);
	ans = min(ans, res);
	return res;
}

void simulate_anneal()
{
	point cur(rand(0, 10000), rand(0, 10000));
	for(double t=5000;t>1e-4;t*=0.99)
	{
		point now(rand(cur.fi - t, cur.fi + t), rand(cur.se - t, cur.se + t));
		double dt = cal(now) - cal(cur);
		if(exp(- dt / t) > rand(0, 1)) cur = now;
	}
	
}

int main()
{
	ans = 1e9;
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%lf%lf",&a[i].fi,&a[i].se);
	for(int i=0;i<100;i++) simulate_anneal();
	printf("%.0lf",ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值