0/1分数规划

2024-08-12

通过二分法求解0/1分数规划问题

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
struct Pair
{
    int a, b;
    double y;
} p[1005];
bool cmp(Pair a, Pair b)
{
    return a.y > b.y;
}
int n, k;
bool check(double x)
{
    for (int i = 0; i < n; i++)
        p[i].y = p[i].a * 1.0 - x * p[i].b;
    sort(p, p + n, cmp);
    double f = 0;
    for (int i = 0; i < k; i++)
        f += p[i].y;
    return f <= 0;
}
int main()
{
    while (scanf("%d%d", &n, &k) == 2 && n + k)
    {
        k = n - k;
        for (int i = 0; i < n; i++)
            scanf("%d", &p[i].a);
        for (int i = 0; i < n; i++)
            scanf("%d", &p[i].b);
        double l = 0, r = 0;
        for (int i = 0; i < n; i++)
            r += p[i].a;
        for (int i = 0; i < 50; i++)
        {
            double mid = l + (r - l) / 2;
            if (check(mid))
                r = mid;
            else
                l = mid;
        }
        printf("%d\n", (int)(100 * (l + 0.005)));
    }
    return 0;
}