求助模拟退火,分数飘忽不定
查看原帖
求助模拟退火,分数飘忽不定
701221
Chr0n1CleC楼主2022/8/12 18:08
#include<bits/stdc++.h>
using namespace std;
#define N 1009

struct node
{
	int x, y, w;	
}a[N];

double T = 1e17;

int n;

double ansx, ansy, dis;

double Rand() {return 1.0 * rand() / RAND_MAX;} 

double calc(double x, double y)
{
	double ret = 0;
	for (int i = 1;i <= n;i ++)
	{
		double nx = a[i].x - x, ny = a[i].y - y;
		ret += sqrt(nx * nx + ny * ny) * a[i].w;
	}
	if (ret < dis)
		ansx = x, ansy = y, dis = ret;//更新答案 
	return ret;
}//平衡函数 

int main()
{
	srand(time(0));
	scanf("%d", &n);
	for (int i = 1;i <= n;i ++)
		scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].w), ansx += a[i].x, ansy += a[i].y;
	double x, y;
	ansx /= n << 1, ansy /= n << 1, dis = calc(ansx, ansy);
	x = ansx, y = ansy;
	while (1.0 * clock() / CLOCKS_PER_SEC < 0.9)
	{
		T = 1e13;
		while (T > 1e-13)
		{
			double nx = x + T * (Rand() * 2 - 1), ny = y + T * (Rand() * 2 - 1);
			double f = calc(nx, ny) - calc(x, y);
			if (exp(-f / T) > Rand())
				x = nx, y = ny;
			T *= 0.9999;
		}
		for (int i = 1;i <= n;i ++)
		{
			double nx = ansx + T * (Rand() * 2 - 1), ny = ansy + T * (Rand() * 2 - 1);
			calc(nx, ny); 
		}
	}
	printf("%.3lf %.3lf", ansx, ansy);
	
	return 0;
}

2022/8/12 18:08
加载中...