二分查找之放弃考试

二分查找之放弃考试_第1张图片

将0/1分数规划问题转化为二分查找问题

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int a[1005],b[1005];
double temp[1005];
int n,k;
bool check(double v)
{
    for( int i = 0; i < n; i++ )
        temp[i] = a[i] -v *b[i];
    sort(temp, temp+n);
    double sum = 0.0;
    for( int i = k; i < n; i++ )
        sum += temp[i];
    if( sum >= 0 )
        return true;
    else
        return false;
}
int main()
{
    while(cin >> n >>k, n!=0)
    {
    for( int i = 0; i < n; i++ )
        cin >> a[i];
    for( int i = 0; i < n; i++ )
        cin >> b[i];
    double left = 0, right = 1;
    while( (right - left) > 1e-6 )
    {
        double mid = left + (right - left)/2.0;
        if( check( mid ) )
        {
            left = mid;
        }
        else
            right = mid;
    }
    printf("%.0f\n",100*left);
    }
    return 0;
}

你可能感兴趣的:(二分查找)