题目链接:http://poj.org/problem?id=2976
01分数规划主要是理解F(L)函数
比如我们要求R的最大值的时候 ,如果F(L)能取到一个大于0的数,那么就可以得到在这个选择的情况下R的值大于L的值
顺便提一下:如果和别人的对拍没有任何问题,但POJ还是WA的话,看看是不是输出用的%lf,POJ的G++输出用lf会wa,以上
二分法:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 1000 + 5;
const double esp = 1e-9;
double A[maxn],B[maxn],C[maxn];
int main(){
int n,k;
// freopen("rand.txt","r",stdin);
while( ~sf("%d %d",&n,&k) ){
if(!n && !k) break;
for(int i = 0;i < n;++i) sf("%lf",&A[i]);
for(int i = 0;i < n;++i) sf("%lf",&B[i]);
double l = 0,r = 1,mid,ret;
while(fabs(l - r) > esp){
mid = (l + r) / 2.0;
for(int i = 0;i < n;++i) C[i] = A[i] - B[i] * mid;
sort(C,C + n);
ret = 0;
for(int i = k;i < n;++i) ret += C[i];
if( ret < esp) r = mid;
else l = mid;
}
pf("%.0lf\n",mid * 100);
}
return 0;
}
迭代法:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 1000 + 5;
const double esp = 1e-9;
double A[maxn],B[maxn],C[maxn];
int D[maxn];
bool cmp(const int& a,const int& b){
return C[a] < C[b];
}
int main(){
int n,k;
// freopen("rand.txt","r",stdin);
while( ~sf("%d %d",&n,&k) ){
if(!n && !k) break;
for(int i = 0;i < n;++i) sf("%lf",&A[i]);
for(int i = 0;i < n;++i) sf("%lf",&B[i]);
double ans = 0,tmp = 20,up,low;
while(fabs(ans - tmp) > esp){
ans = tmp;
for(int i = 0;i < n;++i) C[i] = A[i] - B[i] * tmp,D[i] = i;
sort(D,D + n,cmp);
up = low = 0;
for(int i = k;i < n;++i) up += A[D[i]],low += B[D[i]];
tmp = up / low;
}
pf("%.0lf\n",ans * 100);
}
return 0;
}