【包含内容】
0/1分数规划
一般形式: 然后选择做多k 个或 至少k 个 , 这样的数 删去类的 使得 结果 R 最大 , 最优的问题.
我们先定义一个函数F(L):= ,显然这只是对目标式的一个简单的变形。分离参数,得到F(L):=sigma((。这时我们就会发现,如果L已知的话,a[i]-L*b[i]就是已知的,当然x[i]是未知的。记d[i]=a[i]-L*b[i],那么F(L):=
一般采用 二分答案, L 检索 F[l] 与 0 的关系 来判断 L 是否是最优
F(L)= 即
也就是说,如果一个方案使得F(L)>0 说明了这组方案可以得到一个比现在的L更优的一个L,
既然有一个更优的解,那么为什么不用呢?
F(L) < 0 说明 此时 答案过大 .
例如 Poj 2976
http://poj.org/problem?id=2976
选择 k 个删除使得的答案最大 , 采用二分答案. 判优
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <string.h>
//#include <bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
typedef long long ll;
const int maxn = 1e5+10;
using namespace std;
const double esp = 1e-5;
int n,k;
double a[maxn],b[maxn],s[maxn];
int main()
{
while(~scanf("%d %d",&n,&k))
{
if(n==0&&k==0) break;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(s,0,sizeof(s));
rep(i,1,n+1)
scanf("%lf",&a[i]);
rep(i,1,n+1)
scanf("%lf",&b[i]);
double l = 0.0;
double r = 1000000.0;
while( l+esp < r)
{
double mid = (l+r)*1.0/2;
rep(i,1,n+1)
s[i] = a[i]-mid*b[i];
sort(s+1,s+n+1);
double sum =0;
rep(i,k+1,n+1) sum+=s[i];
if( sum >=0)
l = mid;
else
r = mid;
}
printf("%d\n",(int)(l*100+0.5));
}
return 0;
}
例2 :牛客网暑期ACM多校训练营(第五场)
A
链接:https://www.nowcoder.com/acm/contest/143/A
来源:牛客网
Kanade selected n courses in the university. The academic credit of the i-th course is s[i] and the score of the i-th course is c[i].
At the university where she attended, the final score of her is
Now she can delete at most k courses and she want to know what the highest final score that can get.
输入描述:
The first line has two positive integers n,k
The second line has n positive integers s[i]
The third line has n positive integers c[i]
输出描述:
Output the highest final score, your answer is correct if and only if the absolute error with the standard answer is no more than 10-5
示例1
输入
复制
3 1
1 2 3
3 2 1
输出
复制
2.33333333333
说明
Delete the third course and the final score is
备注:
1≤ n≤ 105
0≤ k < n
1≤ s[i],c[i] ≤ 103
选择 至多K 个 删除, 那么 排序后 从后面选择 n-k 个 , 然后 依次比较前k 个是否选择
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
typedef long long ll;
const int maxn = 1e5+10;
using namespace std;
const double esp = 1e-5;
int n,k;
double a[maxn];
double b[maxn];
double s[maxn];
bool judge(double mid)
{
rep(i,1,n+1)
s[i] = a[i]-mid*b[i];
sort(s+1,s+n+1);
double sum = 0;
rep(i,k+1,n+1)
sum+=s[i];
double mmx = sum;
rep(i,1,k+1)
mmx = max(sum+s[i],mmx);
if(mmx>=0)
return true;
return false;
}
int main()
{
scanf("%d %d",&n,&k);
rep(i,1,n+1)
scanf("%lf",&b[i]);
rep(i,1,n+1)
scanf("%lf",&a[i]);
double l =0.0 , r = 1.0;
rep(i,1,n+1)
{
a[i] = a[i]*b[i];
r = max(a[i],r);
}
while(l +esp <r)
{
double mid = (l+r)*1.0/2;
if(judge(mid))
l = mid;
else
r = mid;
// cout<<l<<" "<<r<<endl;
}
//cout<<l<<" "<<r<<endl;
printf("%.10f\n",l);
return 0;
}