[洛谷P1337][JSOI2004]平衡点 / 吊打XXX

本文介绍了一种使用模拟退火算法解决绳结平衡位置的问题,通过多次迭代寻找最优解,适用于NOIP竞赛准备。文章详细展示了C++代码实现过程,包括关键函数如距离计算、随机数生成等。

题目大意:有$n$个重物,每个重物系在一条绳子上。所有绳子系在一起,问绳结最终平衡于何处。

题解:$NOIP$前学学模拟退火,但发现我脸好黑啊。。。

卡点:脸黑

 

C++ Code:

#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <ctime>
#define maxn 1010
int Tim = 22;
const int __Tim = 2000;
const double eps = 1e-6, __eps = 1e-4;
const double k = 0.995, Temp = 500;
inline double abs(double a) {return a < 0 ? -a : a;}
inline double dis(double x, double y) {return sqrt(x * x + y * y);}
inline double RAND() {return static_cast<double> (rand()) / RAND_MAX;}

int n;
struct point {
	double x, y, w;
	inline void operator += (const point &rhs) {
		x += rhs.x;
		y += rhs.y;
		w += rhs.w;
	}
	inline void operator /= (const double &rhs) {
		x /= rhs;
		y /= rhs;
	}
} s[maxn], ans;

inline double calc(point &lhs) {
	lhs.w = 0;
	for (register int i = 1; i <= n; i++) {
		lhs.w += dis(lhs.x - s[i].x, lhs.y - s[i].y) * s[i].w;
	}
	return lhs.w;
}
void SA() {
	double T = Temp, del;
	point now = ans, nxt;
	while (T > eps) {
		nxt.x = now.x + T * (2 * RAND() - 1);
		nxt.y = now.y + T * (2 * RAND() - 1);
		del = calc(nxt);
		if ((del < now.w) || exp((now.w - nxt.w) / T) > RAND()) now = nxt;
		if (del < ans.w) ans = nxt;
		T *= k;
	}
	int Tim = __Tim;
	now = ans;
	T = __eps;
	while (Tim --> 0) {
		nxt.x = now.x + T * (2 * RAND() - 1);
		nxt.y = now.y + T * (2 * RAND() - 1);
		del = calc(nxt);
		if ((del < now.w) || exp((now.w - nxt.w) / T) > RAND()) now = nxt;
		if (del < ans.w) ans = nxt;
	}
}

int main() {
	srand(20040826);
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%lf%lf%lf", &s[i].x, &s[i].y, &s[i].w);
		ans += s[i];
	}
	ans /= n; calc(ans);
	while (Tim --> 0) SA();
	printf("%.3lf %.3lf\n", ans.x, ans.y);
	return 0;
}

  

转载于:https://www.cnblogs.com/Memory-of-winter/p/9920406.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值