Strange fuction-模擬退火法
Strange fuction
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10439 Accepted Submission(s): 6984
Problem Description
Now, here is a fuction:
F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100)
Can you find the minimum value when x is between 0 and 100.
Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has only one real numbers Y.(0 < Y <1e10)
Output
Just the minimum value (accurate up to 4 decimal places),when x is between 0 and 100.
Sample Input
2 100 200
Sample Output
-74.4291 -178.8534
Author
Redow
模擬退火nb!!!!!!!!
先隨機去一個值,然後隨機移動,看是否能得到更優解,如果是,更新當前點為更優點
每次隨機移動的長度在縮短,這樣保證了跳出區域性最優解(極值和最值的區別不用說了吧)
其實這樣也有可能出現找到的是極值不是最值的情況(但是概率比較小),
所以可以一次隨機好多值,更新答案,這樣最後取最優解,
相當於讓你自己做一道題,然後雖然你很nb,但是你也有可能做錯,
那麼現在拉上一群人一起做,這樣出錯的概率就小多了,
/*好像某個什麼cpu裡的糾錯系統也是這個想法來著*/
複雜度分析了下每次乘delta,那麼t*delta^x<=Esp
這樣或者說
得,log級別的,增長肯定不快
Esp = 1e-6 1e-8
10^1 ->797 10^1 ->1025
10^10 ->1823 10^10 ->2051
10^19 ->2849 10^19 ->3077
這裡計算的是單純的while迴圈的執行次數,如果有n個初始值每個初始值每次瞎跑k次
那麼複雜度就是O(x*n*k)咯,大概吧
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const double Esp = 1e-6,initT = 100,inf = 1e18,delta = 98e-2;
///Esp-->精度,initT-->初始步長,inf-->最大值,delta-->步長每次縮短的係數
const int k = 10;
///每次隨機跑動幾次
double Pow(double a,int b){///快速冪求a^b
double ans = 1;
while(b){
if(b&1)
ans *= a;
a*=a;
b>>=1;
}
return ans;
}
double Rand(){///隨機數輸出一個概率範圍是[-1,1]
return rand()&1 ? 1.0*rand()/RAND_MAX : -1.0*rand()/RAND_MAX;
}
double Fun(double x,double y){///題目中的函式
return 6*Pow(x,7)+8*Pow(x,6)+7*Pow(x,3)+5*Pow(x,2)-y*x;
}
double Sovle(double y){///模擬退火
double t = initT,ans = inf;///t-->初始溫度(步長),ans-->答案
double x = fabs(Rand())*100;///生成原始解,[0,100]
while(t>Esp){///步長咯
double tfx = Fun(x,y);///函式值
for(int i=0;i<k;i++){///隨機瞎跑,取最優解
double tx = x + Rand()*t;///跑動範圍(delta x) [-t,t],即最大步長內
if( tx - 0 >= Esp && tx - 100 <= Esp){///在[0,100]範圍內
double ttfx = Fun(tx,y);///這次跑出去得到的函式值
if(ttfx < tfx){///如果比較優秀
tfx = ttfx;
x = tx;
}
}
ans = min(ans,tfx);///更新答案
}
t *= delta;///步長縮短
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
double y;
scanf("%lf",&y);
printf("%.4f\n",Sovle(y));
}
return 0;
}