模拟退火 (TJOI分金币)
模拟退火真好用
AC代码
#include<bits/stdc++.h>
#define D double
#define RE register
#define P for(RE int _=1;_<500;_++)
using namespace std;
const int Maxn=1e3+5;
const int inf=1<<30;
inline int R()
{
char c;int res;
while((c=getchar())>'9'||c<'0');res=c-'0';
while((c=getchar())>='0'&&c<='9') res=res*10+c-'0';
return res;
}
inline void W(int x)
{
if(x>9) W(x/10);
putchar('0'+x%10);
}
int a[Maxn],T,n,S=inf;
inline int cheak()
{
int res1=0,res2=0;
for(RE int i=1;i<=n/2;i++)
res1+=a[i];
for(RE int i=n/2+1;i<=n;i++)
res2+=a[i];
return abs(res1-res2);
}
inline void DFS()
{
D L=1e-9;int x,y,res;
for(D T=5000;T>L;T*=0.9123)
{
x=rand()%n+1;y=rand()%n+1;
swap(a[x],a[y]);
res=cheak();
if(res<S) S=res;
else if(exp((S-res)/T)<(D)rand()/RAND_MAX) swap(a[x],a[y]);
}
}
int main()
{
srand(14456513);
T=R();
while(T--)
{
S=inf;
n=R();
for(int i=1;i<=n;i++)
a[i]=R();P DFS();
W(S);puts("");
}
}
这个就当做板子用
- 对于只退火100遍
wa 1个点
- 退火50遍
wa 2个点
(以下都是退火50遍)
- delta变成0.9
wa 3个点
- delta=0.9 T=360000 (这里最里面循环数一致)
wa 5个点
- 符合上面的条件,将随机数改变成19260817
wa 7个点
- delta=0.9123 T=5000 将随机数改变成19260817
wa 2个点
并且对于非srand(time(0))
每次出的随机数都是一样的
综上所述
退火十分靠运气牛B