Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 14, 2016 17:03
Show Gist options
  • Save dgodfrey206/4b6f6ee5c16e982f60b7d793ae57bf47 to your computer and use it in GitHub Desktop.
Save dgodfrey206/4b6f6ee5c16e982f60b7d793ae57bf47 to your computer and use it in GitHub Desktop.
#include <vector>
#include<numeric>
#include<climits>
#include <algorithm>
#include<utility>
#include<iostream>
using namespace std;
#define check(n,lim)(0<=(n)&&(n)<=(lim))
// Brute force
vector<int>res={INT_MAX,INT_MIN};
struct ElevatorLimit {
vector<int> getRange(vector<int> enter, vector<int> exit, int physicalLimit) {
int n=enter.size();
bool found=false;
for(int num=0;num<=physicalLimit;++num){
bool valid = true;
int count=num;
for(int i=0;i<n;++i){
count = count - exit[i] + enter[i];
if (!check(count-enter[i],physicalLimit)||!check(count,physicalLimit))
{valid=false; break;}
}
if (valid) {
found=true;
res[0]=min(res[0],num);
res[1]=max(res[1],num);
}
}
if (!found)
return{};
return res;
}
};
// Optimized
template<class P>
int my_lower_bound(int lo, int hi, P p) {
while (lo < hi) {
int mid = lo + (hi-lo)/2;
if (p(mid) == true)
hi = mid;
else
lo = mid+1;
}
if (p(lo) == false)
return -1; // p(x) is false for all x in S!
return lo;
}
template<class P>
int my_upper_bound(int lo, int hi, P p) {
while (lo < hi) {
int mid = lo + (hi-lo+1)/2; // note: division truncates
if (p(mid) == true)
lo = mid;
else
hi = mid-1;
}
if (p(lo) == false)
return -1; // p(x) is true for all x in S!
return lo; // lo is the greatest x for which p(x) is false
}
template<class P>
pair<int,int> my_equal_range(int lo, int hi, P&&p) {
return make_pair(my_lower_bound(lo,hi,p),
my_upper_bound(lo,hi,p)
);
}
struct ElevatorLimit {
vector<int> getRange(vector<int> enter, vector<int> exit, int limit) {
auto p = my_equal_range(0, limit, [&](int n) {
int count=n;
for(size_t i=0;i<enter.size();++i){
count = count - exit[i] + enter[i];
if (!check(count-enter[i], limit) || !check(count,limit))
return false;
}
return true;
});
if (p.first == -1 || p.second == -1) return {};
return {p.first, p.second};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment