tle 2和7 求救

P2440 木材加工

want_AC_ing @ 2024-09-17 17:01:14

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
ll a[N];

int main()
{
    ll n,k;
    cin >> n >> k;
    ll cnt = 0;
    for(int i=1;i<=n;i++) cin >> a[i],cnt += a[i];
    if(cnt<k) cout << 0;
    else 
    {
        ll l = 1,r = 1e8+1;
        ll mid;
        while(l<r)
        {
            mid = (l+r)/2;
            cnt = 0;
            for(int i=1;i<=n;i++) cnt+= a[i]/mid;
            if(cnt<k) r = mid-1;
            else l = mid;
            //cout << mid<<' '<<l<<' '<<r<< endl;
        }
        cout << l;
    }
    return 0;
}

by __Segment__ @ 2024-09-17 17:04:50

@want_AC_ing

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
ll a[N];

int main()
{
    ll n,k;
    cin >> n >> k;
    ll cnt = 0;
    for(int i=1;i<=n;i++) cin >> a[i],cnt += a[i];
    if(cnt<k) cout << 0;
    else 
    {
        ll l = 1,r = 1e8+1;
        ll mid;
        while(l<r)
        {
            mid = (l+r+1)/2;
            cnt = 0;
            for(int i=1;i<=n;i++) cnt+= a[i]/mid;
            if(cnt<k) r = mid-1;
            else l = mid;
            //cout << mid<<' '<<l<<' '<<r<< endl;
        }
        cout << l;
    }
    return 0;
}

by __Segment__ @ 2024-09-17 17:05:36

@want_AC_ing

把mid=(l+r)/2改成(l+r+1)/2,不然有可能在只剩两个数的时候一直去左边的数导致tle


by want_AC_ing @ 2024-09-17 17:27:17

@liuyuxuan2023 感谢,明白了


|