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\)我自己造的数据

转载于:https://www.cnblogs.com/AKMer/p/9594350.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值