求助模拟退火(玄学
查看原帖
求助模拟退火(玄学
226113
火羽白日生楼主2020/8/13 14:53
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <stdlib.h>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>

//#pragma GCC optimize(2)  //吸氧
//#pragma GCC optimize(3,"Ofast","inline")  //吸臭氧

typedef long long ll;
typedef unsigned long long ull;
using namespace std;

inline int read(){
    char ch=getchar();
    int x=0,w=1;
    while(ch<'0'||ch>'9'){
        if(ch=='-')
            w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=(x<<3)+(x<<1)+(ch^48);
        ch=getchar();
    }
    return x*w;
}

int n,T;
double ansx,ansy,ans,ax,ay;
struct node{
    double x,y;
}node[100005];

void init(){
    ax=0.0;ay=0.0;
    ans=1e9;
}

double work_dis(double xx,double yy){
    double res=0.0;
    for(int i=1;i<=n;i++){
        double tx=xx-node[i].x,ty=yy-node[i].y;
        res+=sqrt(tx*tx+ty*ty);
    }
    return res;
}

void simulate_anneal(){
    double temp=3000,delta=0.996;
    double xx=ansx,yy=ansy;
    while(temp>1e-15){
        double tx=xx+(rand()*2-RAND_MAX)*temp;
        double ty=yy+(rand()*2-RAND_MAX)*temp;
        double now_ans=work_dis(tx,ty);
        double now_delta=now_ans-ans;
        if(now_delta<0){
            ansx=tx;xx=tx;
            ansy=ty;yy=ty;
            ans=now_ans;
        }
        else if(exp(-now_delta/temp)*RAND_MAX>rand()){
            xx=tx;
            yy=ty;
        }
        temp*=delta;
    }
}

void work(){
    ansx=ax/(double)n;
    ansy=ay/(double)n;
    for(int i=1;i<=10;i++)
        simulate_anneal();
}

int main(int argc, const char * argv[]) {
    srand(time(0));
    T=read();
    for(int i=1;i<=T;i++){
        n=read();
        init();
        for(int j=1;j<=n;j++){
            cin>>node[j].x>>node[i].y;
            ax+=node[j].x;
            ay+=node[j].y;
        }
        work();
        cout<<ans<<"\n";
        if(i!=T) cout<<"\n";
    }
    return 0;
}

搞不明白哪里炸了啊

没过样例(哭

2020/8/13 14:53
加载中...