1. 程式人生 > >2899 Strange fuction【爬山演算法 || 模擬退火】

2899 Strange fuction【爬山演算法 || 模擬退火】

Time limit 1000 ms
Memory limit 32768 kB

Now, here is a fuction:
$F(x) = 6 * x7+8*x6+7x3+5*x2-yx (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.

題目分析

這題正解本來是二分來著

//爬山演算法
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef double dd;
#define
T 100
//初始溫度 #define delta 0.999//降溫係數 #define eps 1e-8//溫度下限 int read() { int x=0,f=1; char ss=getchar(); while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();} while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();} return x*f; } int Q; dd y,ans; dd dx[2]={1.0,-1.0}; dd qpow(
dd a,int k){ dd res=1.0; while(k>0){ if(k&1)res*=a; a*=a; k>>=1;} return res;} dd F(dd x){ return 6.0*qpow(x,7)+8.0*qpow(x,6)+7.0*qpow(x,3)+5.0*qpow(x,2)-y*x;} int main() { Q=read(); while(Q--) { scanf("%lf",&y); dd t=T,r=delta,x=100.0; while(t>eps) { dd nx=-1.0; while(nx<0||nx>100) nx=x+dx[rand()%2]*t; if(F(nx)<F(x)) x=nx; t*=r; } printf("%.4lf\n",F(x)); } }
//模擬退火
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
typedef double dd;
#define T 100//初始溫度
#define delta 0.999//降溫係數
#define eps 1e-8//溫度下限

int read()
{
    int x=0,f=1;
    char ss=getchar();
    while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
    while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
    return x*f;
}

int Q;
dd y;
dd dx[2]={1.0,-1.0};

dd qpow(dd a,int k){ dd res=1.0; while(k>0){ if(k&1)res*=a; a*=a; k>>=1;} return res;}
dd F(dd x){ return 6.0*qpow(x,7)+8.0*qpow(x,6)+7.0*qpow(x,3)+5.0*qpow(x,2)-y*x;}

int main()
{
    Q=read();
    while(Q--)
    {
        scanf("%lf",&y);
        
        dd t=T,x=100.0,ans=F(x);
    	while(t>eps)
    	{
        	dd nx=-1.0;
    		while(nx<0||nx>100) nx=x+dx[rand()%2]*t;
        	dd dE=ans-F(nx);
        	if(dE>=0) x=nx,ans=F(nx);
        	else if( exp(dE/t) > ((dd)rand()/(dd)RAND_MAX) ) x=nx;
        	//以一定概率接收非更優解
        	t*=delta;
    	}
        printf("%.4lf\n",ans);
    }
    return 0;
}