Watching Video
binary search
Problem Link
#include <iostream>
using namespace std;
long n, d;
long arr[1000001];
bool func(int t)
{
long long tmp=0;
for(int i=1;i<=t;i++)
tmp+=arr[i];
t++;
while(tmp>=d && t < n+1) {
if(tmp <d)
return false;
tmp -= d;
tmp+=arr[t];
t++;
}
if(t==n+1)
return true;
else
return false;
}
int bs(int low, int high)
{
int mid;
while(low < high)
{
mid = (low + high) / 2;
if(func(mid))
{
high = mid;
}
else
{
low = mid + 1;
}
}
return high;
}
int main()
{
cin >> n >> d;
for(int i = 1; i <= n; i++)
{
cin >> arr[i];
}
for(int i = n;i > 0;i--) {
if(arr[i] == 0)
n--;
else
break;
}
int pos = bs(0, n);
cout << pos << endl;
return 0;
}
binary search
Problem Link
#include <iostream>
using namespace std;
long n, d;
long arr[1000001];
bool func(int t)
{
long long tmp=0;
for(int i=1;i<=t;i++)
tmp+=arr[i];
t++;
while(tmp>=d && t < n+1) {
if(tmp <d)
return false;
tmp -= d;
tmp+=arr[t];
t++;
}
if(t==n+1)
return true;
else
return false;
}
int bs(int low, int high)
{
int mid;
while(low < high)
{
mid = (low + high) / 2;
if(func(mid))
{
high = mid;
}
else
{
low = mid + 1;
}
}
return high;
}
int main()
{
cin >> n >> d;
for(int i = 1; i <= n; i++)
{
cin >> arr[i];
}
for(int i = n;i > 0;i--) {
if(arr[i] == 0)
n--;
else
break;
}
int pos = bs(0, n);
cout << pos << endl;
return 0;
}
Comments
Post a Comment