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;
}
首先随机一个点,然后设步长为一个比较大的数,然后试着向上下左右走步长的距离,如果能走,就走到那个点,如果四个方向都走不了,就把步长除以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;
}
相关文章推荐
- poj 2420 A Star not a Tree? 随机化变步长贪心
- poj 2420 A Star not a Tree?(贪心+求多边形费马点)
- POJ2420 A Star not a Tree?
- POJ 2420 A Star not a Tree?
- poj 2420 A Star not a Tree?(模拟退火)
- POJ2420——A Star not a Tree?
- poj 2420 A Star not a Tree?(模拟退火)
- POJ 2420 A Star not a Tree? (简单模拟退火)
- 【POJ 2420】A Star not a Tree?
- POJ 2420 A Star not a Tree?(计算几何 多边形的费马点 模拟退火)
- poj 2420 A Star not a Tree?(模拟退火求费马点)
- POJ 2420 A Star not a Tree? (计算几何-费马点)
- POJ 2420 A Star not a Tree? 费马点 计算几何 模拟退火
- poj 2420 A Star not a Tree?
- poj 2420 A Star not a Tree?
- POJ 2420 A Star not a Tree?【爬山法】
- poj 2420 A Star not a Tree?
- POJ 2420 A Star not a Tree?
- [POJ 2420] A Star not a Tree?
- POJ 2420 A Star not a Tree?