模拟退火算法

来源:互联网 发布:大数据自动阅卷系统 编辑:程序博客网 时间:2024/04/26 06:05

http://poj.org/problem?id=2420
题目大意:
给出平面上n个点,求到所有点距离和最短的点,输出该距离和。

#include <stdio.h>#include <stdlib.h>#include <math.h>#include <string.h>#include <time.h>struct pos{double x,y;}p[101];int n;///////// 计算点x到各点距离之和 /////////////double dis(pos x) {    double d=0;    for(int i=0;i<n;i++)        d+=hypot(p[i].x-x.x,p[i].y-x.y);    return d;}///////// 模拟退火 /////////////double SA() {    double t,mi,tmp;// 温度,最小距离,临时距离    pos p,tp;       // 最优点,临时点    int k=0;        // 记录连续未接受点数    p.x=p.y=5000;   // 初始化最优点为中心点    mi=dis(p);    srand(1);    ///// 初始化温度,温度以一定速率减小,温度小于临界(1) 或 连续超过一定数量(20)个临时点未被接受时 终止 /////    for(t=5000;t>1&&k++<20;t*=0.93){        ///// 在p周围一定 范围 内生成临时点, 该范围随温度t降低逐渐减小 /////        tp.x=p.x+(rand()&1?1:-1)*rand()*t/RAND_MAX;        tp.y=p.y+(rand()&1?1:-1)*rand()*t/RAND_MAX;        tmp=dis(tp);        ///// 若生成的临时点距离小于当前最小,更新最优点 /////        ///// 否则,以一定 概率 接受该临时点,该概率随温度t降低逐渐减小 /////        if(tmp<mi||rand()*10000.0/RAND_MAX<t){p=tp;mi=tmp;k=0;}    }return mi;}int main(){    scanf("%d",&n);    for(int i=0;i<n;i++)        scanf("%lf%lf",&p[i].x,&p[i].y);    printf("%.0f\n",SA());    return 0;}

题意:在三维空间内给出一些行星的坐标,求出把所有点都包含在内的球的最小半径。

#include<iostream>  #include<cstdio>  #include<algorithm>  #include<cstring>  #include<cmath>  using namespace std;  const double eps=1e-7;  struct node {double x,y,z;}A[35],p;  int n;  double dis(node a,node b)  {      return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z));  }  double solve()  {      double step=100,ans=1e30,mt;      p=(node){50,50,50};    int s=0,k=0;      for(double t=50;t>eps;t*=0.98){          for(int i=0;i<n;i++)              if(dis(p,A[s])<dis(p,A[i]))s=i;          mt=dis(p,A[s]);          ans=min(ans,mt);        //以一定的比例向它移动         p.x+=(A[s].x-p.x)/mt*t;          p.y+=(A[s].y-p.y)/mt*t;          p.z+=(A[s].z-p.z)/mt*t;      }printf("%.5f\n",ans);}  int main(){      while(~scanf("%d",&n),n){          for(int i=0;i<n;i++)              scanf("%lf%lf%lf",&A[i].x,&A[i].y,&A[i].z);          solve();    }return 0;  }  
2 0
原创粉丝点击