模拟退火2 P3878 [TJOI2010]分金币
作者:互联网
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 ll ans,n,sum; 5 int a[100]; 6 7 int f() 8 { 9 int t=0; 10 for(int i=1;i<=n/2;i++)t+=a[i]; 11 return abs(sum-2*t); 12 } 13 void mnth() 14 { 15 for(double T=5000;T>1e-15;T*=0.945) 16 { 17 int x1=rand()%n+1; 18 int x2=rand()%n+1; 19 swap(a[x1],a[x2]); 20 int nowsum=f(); 21 if(nowsum<ans)ans=nowsum; 22 else if(exp((ans-nowsum)/T)*RAND_MAX<rand())swap(a[x1],a[x2]); 23 } 24 } 25 int main() 26 { 27 ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 28 int T; 29 cin>>T; 30 while(T--) 31 { 32 ans=INT_MAX,sum=0; 33 cin>>n; 34 for(int i=1;i<=n;i++)cin>>a[i],sum+=a[i]; 35 int x=1000; 36 while(x--)mnth(); 37 cout<<ans<<endl; 38 } 39 return 0; 40 }
标签:rand,nowsum,int,sum,P3878,模拟退火,ans,TJOI2010,ll 来源: https://www.cnblogs.com/matt-su/p/16096311.html