Architect's Dilemma..!
Binary Search
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n, w, a[100005], pre[100005], maxx[100005];
bool f(int x)
{
for(int i = 0, j = x; j <= n; j++, i++)
{
if((x * maxx[j] - (pre[j] - pre[i])) <= w)
return 1;
}
return 0;
}
int main()
{
cin >> n >> w;
for(int i = 1; i <= n; i++)
cin >> a[i];
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; i++)
{
pre[i] = pre[i - 1] + a[i];
maxx[i] = max(maxx[i - 1], a[i]);
}
int l = 1, r = n, ans;
while(l <= r)
{
int mid = (l + r) / 2;
if(f(mid))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
cout << ans << endl;
return 0;
}
Comments
Post a Comment