It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
我试图理解模拟退火的概念,所以我试图实现它来对数字排序。我不确定这是否是模拟退火的概念正确实现在这种情况下,有人能指导我如何正确地执行它吗?
在这种情况下,如何改进分数函数另外,我还没能在这里实现温度的概念。请容忍我,因为我是一个编程初学者。

#include<iostream>
#include<vector>
#include<map>
#include<cstdlib>
#include<cmath>
using namespace std;
void print(vector<int> x)
{
  for(int i=0;i<x.size();i++)
  {
     cout<<x[i]<<"->";
  }
  cout<<endl;
}
int score(vector<int> x)
{
   int s=0;
   for(int i=0;i<x.size()-1;i++)
   {
      for(int j=i+1;j<x.size();j++)
      {
        if(x[j]<x[i])
        s++;
      }
   }
   return s;
}
map<vector<int> ,int>h;
int main()
{
  vector<int> x;
  srand(time(0));
  int N=20;// vector size
  for(int i=0;i<N;i++)
  {
    x.push_back(rand()%10000);
  }
  int it=0;
  while(it<5000)
  {
      if(score(x)==0)  // score =0 stop;
      {
         print(x);
         cout<<"done in iterations"<<it<<endl;
         break;
      }
      int a=rand()%N;
      int b=rand()%N;
      swap(x[a],x[b]);
      vector<int>y=x;
      swap(x[a],x[b]);
      if(h.find(y)!=h.end())   continue;
      if(score(x)>score(y))
      {
           x=y;
      }
      //print(x);
      it++;
  }
  return 0;

}

最佳答案

这与模拟退火无关,它只是一种爬山随机排序。模拟退火的关键特性是它偶尔会在搜索中接受一个更糟糕的答案,而您的代码永远不会接受。

关于c++ - 如何使用模拟退火概念提高此代码对数字进行排序的效率? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15638354/

10-11 19:49