模拟退火
  • 板块P1433 吃奶酪
  • 楼主XKJie
  • 当前回复4
  • 已保存回复4
  • 发布时间2022/11/23 20:13
  • 上次更新2023/10/27 01:47:35
查看原帖
模拟退火
197901
XKJie楼主2022/11/23 20:13
#include <bits/stdc++.h>
#define double long double
using namespace std;
const int maxn=20;
const double eps=1e-7;
const double down=0.999;
struct node{
    double x,y;
}a[maxn];
int n,path[maxn];
double ans=99999999999.0;
inline double getdis(){
    double sum=0.0;
    for (int i=0;i<n;i++){
        double dx=a[path[i]].x-a[path[i+1]].x;
        double dy=a[path[i]].y-a[path[i+1]].y;
        sum+=sqrt(dx*dx+dy*dy); 
    }
    return sum;
}
inline void SA(){
    random_shuffle(path+1,path+n+1);
    ans=min(ans,getdis());
    double T=1e5;
    while (T>eps){
        int x=rand()%n+1,y=rand()%n+1;
        double pre=getdis();
        swap(path[x],path[y]);
        double now=getdis();
        double value=now-pre;
        if (value<0) ans=min(ans,now);
        else if (exp(-value/T)*RAND_MAX<=rand()) swap(path[x],path[y]);
        T*=down;
    }
}
int main(){
    //freopen("test.in","r",stdin);
    //freopen("test.out","w",stdout);
    scanf("%d",&n);
    for (int i=1;i<=n;i++) scanf("%Lf%Lf",&a[i].x,&a[i].y);
    for (int i=1;i<=n;i++) path[i]=i;
    while (clock()/CLOCKS_PER_SEC<0.8) SA();
    printf("%.2Lf\n",ans);
    //system("pause");
    return 0;
}
#include <bits/stdc++.h>
#define double long double
using namespace std;
const int maxn=20;
const double eps=1e-7;
const double down=0.999;
struct node{
    double x,y;
}a[maxn];
int n,path[maxn];
double ans=99999999999.0;
inline double getdis(){
    double sum=0.0;
    for (int i=0;i<n;i++){
        double dx=a[path[i]].x-a[path[i+1]].x;
        double dy=a[path[i]].y-a[path[i+1]].y;
        sum+=sqrt(dx*dx+dy*dy); 
    }
    return sum;
}
inline void SA(){
    random_shuffle(path+1,path+n+1);
    ans=min(ans,getdis());
    double T=1e5;
    while (T>eps){
        int x=rand()%n+1,y=rand()%n+1;
        double pre=getdis();
        swap(path[x],path[y]);
        double now=getdis();
        double value=now-pre;
        if (value<0) ans=min(ans,now);
        else if (exp(-value/T)*RAND_MAX<=rand()) swap(path[x],path[y]);
        T*=down;
    }
}
int main(){
    //freopen("test.in","r",stdin);
    //freopen("test.out","w",stdout);
    scanf("%d",&n);
    for (int i=1;i<=n;i++) scanf("%Lf%Lf",&a[i].x,&a[i].y);
    for (int i=1;i<=n;i++) path[i]=i;
    for (int i=1;i<=100;i++) SA();
    printf("%.2Lf\n",ans);
    //system("pause");
    return 0;
}

接楼下贴。
为啥我的卡时寄掉了
前面一份代码过不去 ,全部t掉
甚至把0.8调到0.5也不行
后面一份代码就没有问题
另外这份代码问什么开了o2速度会变快很多(不开a不了),没有大量使用stl啊

2022/11/23 20:13
加载中...