samedi 25 février 2023

How can I correct my `upp` and `low` in my Binary Search? [closed]

I am doing a problem, which states

You are given 3 integers N, TC and TM. You are also given Ai, Bi and Ti for 1 ≤ i ≤ N.
There exist 2 integers AC and AM such that Ai × AC + Bi × AM ≤ Ti for 1 ≤ i ≤ N. Find the greatest value of AC + AM. Note: You may need to use long long in C++ or BigInteger in Java.

My code

#include <iostream>
#include <algorithm>
#include <assert.h>
#include <cmath>

const int N=113;
const long long inf=1e18;

int n;
long long tc, tm;
long long c[N], m[N], t[N];

long long mfn(long long ac)
{
    long long am=inf;
    for (int a=0; a<n; a++)
    {
        am=std::min(am, (long long)(t[a]-c[a]*ac)/m[a]);
    }
    return am;
}
long long driver()
{
    std::cin>>n>>tc>>tm;
    long long ctot, mtot;
    for (int a=0; a<n; a++) 
    {
        std::cin>>c[a]>>m[a]>>t[a];
        ctot+=c[a];
        mtot+=m[a];
    }
    
    long long low=0, upp=tc;
    long long ans=-inf;
    long long ac, am;
    while (low<=upp)
    {
        //cout<<low<<' '<<upp<<' '<<ac<<' '<<am<<' '<<ans<<endl;
        ac=(low+upp)>>1, am=mfn(ac);
        if (ac>=0 && am>=0)
        {
            ac=std::min(ac, tc), am=std::min(am, tm);
            if (ans<ac+am) ans=ac+am;
            if (ctot<=mtot) upp=ac-1;
            else low=ac+1;
        }
        else upp=ac-1;
        //cout<<low<<' '<<upp<<' '<<ac<<' '<<am<<' '<<ans<<endl;
    }
    return tc+tm-ans;
}

int main()
{
    int t;
    std::cin>>t;
    while (t--) std::cout<<driver()<<std::endl;
    return 0;
}

Explanation:
N: The maximum value for n.
inf: 1e18.
n: The number of conditions.
tc, tm: TC and TM.
c[], m[], t[]: Stores A, B and T.
mfn(): Solve for the maximum AM when AC is fixed.
driver(): The function that is used to solve for AC+AM.
ctot, mtot: The total sum of Ai, Bi respectively. I use this to decide how to update low and upp since AMnew=AMold - (Ai / Bi) * x, where x is the increase in AC.
low, upp: Binary Search.
ans: Final answer.
ac, am: AC and AM. main: Main function.

My method is binary search for AC, then solve for the corresponding biggest AM and update the maximum value of AC+AM. The formula I used to find AM is AM = minimum of the floor of (t[a] - c[a] * ac) / m[a]. However, I keep getting Wrong Answer. I think there is a problem in my low and upp, but I don't know what it is. Any help is appreciated. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire