1. 程式人生 > 實用技巧 >【知識點】拉格朗日乘數法

【知識點】拉格朗日乘數法

簡介:

在滿足約束條件$\varphi(x_1 ,x_2 ,\cdots ,x_n )=0$時求$f(x_1 ,x_2 ,\cdots ,x_n )$的極值。

結論:

令$L(x_1 ,x_2 ,\cdots ,x_n )=f(x_1 ,x_2 ,\cdots ,x_n )+\lambda \varphi(x_1 ,x_2 ,\cdots ,x_n )$。

再令$\frac{\partial L}{\partial {x_i}}$為L關於$x_i$的偏導數。(即視其他$x_j$為常量,僅對$x_i$求導)

則方程組

$\begin{cases}\frac{\partial L}{\partial {x_1}}=0\\\frac{\partial L}{\partial {x_2}}=0\\ \cdots \\ \frac{\partial L}{\partial {x_n}}=0 \\ \varphi(x_1 ,x_2 ,\cdots ,x_n )=0\end{cases}$

的某個解$(\lambda_{k},x_{k,1} ,x_{k,2} ,\cdots ,x_{k,n} )$一定對應著f的極值點。

實現:

先通過列舉/二分/三分確定$\lambda$,然後根據題意算出一組合法解更新答案即可。

程式碼(NOI2012騎行川藏):

#include<bits/stdc++.h>
#define maxn 200005
#define maxm 500005
#define inf 0x7fffffff
#define eps 1e-14
#define ll long long
#define rint register int
#define debug(x) cerr<<#x<<": "<<x<<endl
#define
fgx cerr<<"--------------"<<endl #define dgx cerr<<"=============="<<endl using namespace std; struct road{double s,k,v;}A[maxn]; int n; double E; inline int read(){ int x=0,f=1; char c=getchar(); for(;!isdigit(c);c=getchar()) if(c=='-') f=-1; for(;isdigit(c);c=getchar()) x=x*10
+c-'0'; return x*f; } inline int dcmp(double x){return (abs(x)<=eps)?0:(x<0?-1:1);} inline double phi(double lam){ double res=0; for(int i=1;i<=n;i++){ double l=max(A[i].v,0.0),r=1e5; while(dcmp(r-l)>0){ double mid=(l+r)/2.0; if(dcmp(2.0*lam*A[i].k*(mid-A[i].v)*mid*mid-1.0)<=0) l=mid; else r=mid; //printf("%.8lf %.8lf %.8lf\n",2.0*lam*A[i].k*(mid-A[i].v)*mid*mid-1.0,l,r); } res+=A[i].k*(l-A[i].v)*(l-A[i].v)*A[i].s; } //printf("%lf\n",res-E); return res-E; } inline double calc(double lam){ double res=0; for(int i=1;i<=n;i++){ double l=max(A[i].v,0.0),r=1e5; while(dcmp(r-l)>0){ double mid=(l+r)/2.0; if(dcmp(2*lam*A[i].k*(mid-A[i].v)*mid*mid-1)<=0) l=mid; else r=mid; } res+=A[i].s/l; } return res; } int main(){ //freopen("bicycling17.in","r",stdin); n=read(),scanf("%lf",&E); //cout<<n<<":"<<E<<endl; for(int i=1;i<=n;i++) scanf("%lf%lf%lf",&A[i].s,&A[i].k,&A[i].v); double l=0,r=1e5; while(dcmp(r-l)>0){ double mid=(l+r)/2.0; if(dcmp(phi(mid))>=0) l=mid; else r=mid; } //printf("%lf %lf\n",l,r); printf("%.6lf\n",calc(l)); return 0; }
騎行川藏