Created
October 27, 2016 04:07
-
-
Save kartikkukreja/5d9b72ce3588afc4ed47474bfe4bbd74 to your computer and use it in GitHub Desktop.
Queue with min operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class QueueWithMin { | |
private: | |
stack< pair<T, T> > S1, S2; | |
public: | |
void enqueue(T& x) { | |
S2.push(pair<T, T>(x, S2.empty() ? x : min(x, S2.top().second))); | |
} | |
T dequeue() { | |
if (S1.empty()) { | |
while (!S2.empty()) { | |
pair<T, T> top = S2.top(); S2.pop(); | |
top.second = S1.empty() ? top.first : min(top.first, S1.top().second); | |
S1.push(top); | |
} | |
} | |
if (S1.empty()) | |
throw "empty queue"; | |
pair<T, T> top = S1.top(); S1.pop(); | |
return top.first; | |
} | |
T getMin() { | |
if (empty()) | |
throw "empty queue"; | |
return S1.empty() ? S2.top().second : (S2.empty() ? S1.top().second : min(S1.top().second, S2.top().second)); | |
} | |
bool empty() { | |
return S1.empty() && S2.empty(); | |
} | |
int size() { | |
return S1.size() + S2.size(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment