POJ2420:A Star not A Tree?

我对模拟退火的理解:https://www.cnblogs.com/AKMer/p/9580982.html

我对爬山的理解:https://www.cnblogs.com/AKMer/p/9555215.html

题目传送门:http://poj.org/problem?id=2420

这题就是要我们求平面图费马点……

然后我似乎先写了广义费马点……顺序错了……至于对费马点的解释去这里看吧……

BZOJ3680吊打XXX:https://www.cnblogs.com/AKMer/p/9588724.html

时间复杂度:\(O(能A)\)

空间复杂度:\(O(能A)\)

爬山算法代码如下:

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

#define sqr(x) ((x)*(x))

const int maxn=105;

int n;
double ans=1e18,ansx,ansy;

struct computer {
	double x,y;
}p[maxn];

double len() {
	double x=rand()%200000-100000;
	return x/100000;
}

double dis(double x1,double y1,double x2,double y2) {
	return sqrt(sqr(x1-x2)+sqr(y1-y2));
}

double calc(double x,double y) {
	double tmp=0;
	for(int i=1;i<=n;i++)
		tmp+=dis(x,y,p[i].x,p[i].y);//除了这里没有乘权值就跟吊打XXX没有任何区别了
	if(tmp<ans) {ans=tmp;ansx=x;ansy=y;}
	return tmp;
}

int main() {
	srand(time(0));
	scanf("%d",&n);
	for(int i=1;i<=n;i++) {
		scanf("%lf%lf",&p[i].x,&p[i].y);
		ansx+=p[i].x,ansy+=p[i].y;
	}ansx/=n;ansy/=n;double now_x=ansx,now_y=ansy;
	for(int T=1e7;T>=1e-7;T*=0.98) {
		double nxt_x=now_x+len()*T;
		double nxt_y=now_y+len()*T;
		if(calc(nxt_x,nxt_y)<calc(now_x,now_y))
			now_x=nxt_x,now_y=nxt_y;
	}
	printf("%.0lf\n",ans);
	return 0;
}

模拟退火代码如下:

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

#define sqr(x) ((x)*(x))

const int maxn=101;
const double T_0=1e-7;
const double del_T=0.98;

int n;
double ans=1e18,ansx,ansy;

struct computer {
	double x,y;
}p[maxn];

double len() {
	double x=rand()%200000-100000;
	return x/100000;
}

double dis(double x1,double y1,double x2,double y2) {
	return sqrt(sqr(x1-x2)+sqr(y1-y2));
}

double calc(double x,double y) {
	double tmp=0;
	for(int i=1;i<=n;i++)
		tmp+=dis(x,y,p[i].x,p[i].y);
	if(tmp<ans) {ans=tmp;ansx=x;ansy=y;}
	return tmp;
}

void Anneal() {
	double T=10000000,now_x=ansx,now_y=ansy;
	while(T>=T_0) {
		double nxt_x=now_x+len()*T;
		double nxt_y=now_y+len()*T;
		double tmp1=calc(now_x,now_y);
		double tmp2=calc(nxt_x,nxt_y);
		if(tmp2<tmp1||exp((tmp1-tmp2)/T)*RAND_MAX>rand())
			now_x=nxt_x,now_y=nxt_y;
		T*=del_T;
	}
}

int main() {
	srand(time(0));
	scanf("%d",&n);
	for(int i=1;i<=n;i++) {
		scanf("%lf%lf",&p[i].x,&p[i].y);
		ansx+=p[i].x,ansy+=p[i].y;
	}ansx/=n;ansy/=n;Anneal();
	printf("%.0lf\n",ans);
	return 0;
}

因为这题要我们求的答案是总距离(并且还是保存整数位的),所以相对吊打XXX简单多了。两种算法都可以\(A\)我自己造的数据

posted @ 2018-09-05 20:34  AKMer  阅读(169)  评论(0编辑  收藏  举报