您的位置:首页 > 其它

POJ 2420 A Star not a Tree?(随机变步长贪心)

2014-07-23 22:39 357 查看
第一次做随机算法的题目。

首先随机一个点,然后设步长为一个比较大的数,然后试着向上下左右走步长的距离,如果能走,就走到那个点,如果四个方向都走不了,就把步长除以2,直到步长小于某个数为止。

貌似能用这个算法要建立在单峰的基础上?貌似可以用三分做?

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

const int maxn = 110;
const double eps = 1e-8;
double x[maxn], y[maxn];
int n;

int sgn(double x) {return x < -eps ? -1 : x > eps;}

double check(double x0, double y0)
{
double ret = 0;
for (int i = 0; i < n; i++)
ret += sqrt((x[i]-x0)*(x[i]-x0)+(y[i]-y0)*(y[i]-y0));
return ret;
}

int main()
{
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++)
scanf("%lf%lf", &x[i], &y[i]);
double x0 = x[0], y0 = y[0], cur = check(x0, y0);
double step = 1;
while (step > 0.5) {
if (sgn(check(x0+step, y0)-cur) < 0) {
cur = check(x0+step, y0);
x0 += step;
}
else if (sgn(check(x0-step, y0)-cur) < 0) {
cur = check(x0-step, y0);
x0 -= step;
}
else if (sgn(check(x0, y0+step)-cur) < 0) {
cur = check(x0, y0+step);
y0 += step;
}
else if (sgn(check(x0, y0-step)-cur) < 0) {
cur = check(x0, y0-step);
y0 -= step;
}
else
step /= 2;
}
printf("%.0lf\n", check(x0, y0));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: