[模板]模拟退火 / 洛谷 P1337 [JSOI2004]平衡点

[模板]模拟退火 / 洛谷 P1337 [JSOI2004]平衡点

题目

题目描述

如图:有n个重物,每个重物系在一条足够长的绳子上。每条绳子自上而下穿过桌面上的洞,然后系在一起。图中X处就是公共的绳结。假设绳子是完全弹性的(不会造成能量损失),桌子足够高(因而重物不会垂到地上),且忽略所有的摩擦。

问绳结X最终平衡于何处。

注意:桌面上的洞都比绳结X小得多,所以即使某个重物特别重,绳结X也不可能穿过桌面上的洞掉下来,最多是卡在某个洞口处。

img

输入格式

文件的第一行为一个正整数n(1≤n≤1000),表示重物和洞的数目。接下来的n行,每行是3个整数:Xi.Yi.Wi,分别表示第i个洞的坐标以及第 i个重物的重量。(-10000≤x,y≤10000, 0<w≤1000 )

输出格式

你的程序必须输出两个浮点数(保留小数点后三位),分别表示处于最终平衡状态时绳结X的横坐标和纵坐标。两个数以一个空格隔开。

输入输出样例

输入 #1

3
0 0 1
0 2 1
1 1 1

输出 #1

0.577 1.000

代码+注释

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
unsigned seed;

int read() {
	int re = 0;
	char c = getchar();
	bool negt = false;
	while(c < '0' || c > '9')
		negt |= (c == '-') , c = getchar();
	while(c >= '0' && c <= '9')
		re = (re << 1) + (re << 3) + c - '0' , c = getchar();
	seed *= re;
	return negt ? -re : re;
}

const int N = 10010;
struct NodeClass {
	int x , y , m;
}node[N];

int n;
double ansx , ansy;
double minEp = 1e18;//Ep:重力势能的缩写,minEp即最小的重力势能,也就是(搜过的答案中)最稳定的状态,最趋近平衡的状态
const double delta_t = 0.993;
const double originT = 3000;//原温度

double calc_Ep(double nowx , double nowy) {
	double sum = 0;
	for(int i = 1 ; i <= n ; i++) {
		double delx = nowx - node[i].x , dely = nowy - node[i].y;
		sum += std::sqrt(delx * delx + dely * dely) * node[i].m;//求总重力势能,严格来说Ep=mgh,这里省略重力加速度g
	}
	return sum;
}
void simulate_anneal() {
	double x = ansx , y = ansy;
	double t = originT;
	while(t > 1e-14) {
		double nowx = ansx + (rand() * 2 - RAND_MAX) * t;
		double nowy = ansy + (rand() * 2 - RAND_MAX) * t;
		double nowEp = calc_Ep(nowx , nowy);
		double DE = nowEp - minEp;
		if(DE < 0) {//新答案更优
			ansx = x = nowx , ansy = y = nowy;
			minEp = nowEp;
		}
		else if(exp(-DE / t) * RAND_MAX > rand()) {//随机决定是否选择不那么优的答案
			x = nowx , y = nowy;
		}
		t *= delta_t;
	}
}
int main() {
	n = read();
	for(int i = 1 ; i <= n ; i++)
		node[i].x = read() , node[i].y = read() , node[i].m = read();
	
	std::srand(seed);
	
	for(int i = 1 ; i <= 4 ; i++)//多跑几次
		simulate_anneal();
	printf("%.3f %.3f" , ansx , ansy);
	return 0;
}
posted @ 2021-08-20 20:58  追梦人1024  阅读(34)  评论(0编辑  收藏  举报
Live2D