Untitled
unknown
plain_text
17 days ago
2.0 kB
4
Indexable
Never
#include <iostream> #include <set> #include <unordered_map> #include <vector> using namespace std; struct cmp{ bool operator()(const pair<int, int> &a, const pair<int, int> &b) const { if((a.second - a.first) == (b.second - b.first)) { return a.first < b.first; } return (a.second - a.first) > (b.second - b.first); } }; set<pair<int, int>, cmp> space; set<int> locker; unordered_map<int, int> mp; int mid; int n; int remain; void init(int N) { n = N; remain = N; mid = -1; mp.clear(); space.clear(); locker.clear(); locker.insert(0); // sentinel value for easier implementation of the algorithm. 0 is not a valid position in the corridor. 0 is used to represent the left end of the corridor and n+1 is used to represent the right end of the corridor. space.insert(make_pair(1, N)); locker.insert(n+1); // sentinel value for easier implementation of the algorithm. n+1 is not a valid position in the corridor. 0 is used to represent the left end of the corridor and n+1 is used to represent the right end of the corridor. return; } int arrive(int mId) { auto it = space.begin(); auto st = it->first; auto en = it->second; if(st == 1) { mid = 1; space.insert(make_pair(st+1, en)); } else if(en == n) { mid = n; space.insert(make_pair(st, en-1)); } else { mid = (st + en) / 2; space.insert(make_pair(st, mid-1)); space.insert(make_pair(mid+1, en)); } locker.insert(mid); space.erase(make_pair(st, en)); mp[mId] = mid; return mid; } int leave(int mId) { int idx = mp[mId]; auto it = locker.find(idx); auto nex = next(it);//n+1 auto pre = prev(it); //0 auto tmp1 = make_pair(*pre + 1, idx-1); auto tmp2 = make_pair(idx+1, *nex - 1); space.erase(tmp1); space.erase(tmp2); space.insert(make_pair(*pre + 1, *nex - 1)); mp.erase(mId); locker.erase(idx); return n - locker.size(); }
Leave a Comment