Stacks
Authors: Darren Yao, Michael Cao
Contributor: George Pong
A data structure that only allows insertion and deletion at one end.
Resources | ||||
---|---|---|---|---|
CPH | brief description of operations | |||
CSA | Bracket Matching Application |
Stacks
A stack is a Last In First Out (LIFO) data structure that supports three operations, all in time. Think of it like a real-world stack of papers.
C++
push
: adds an element to the top of the stackpop
: removes an element from the top of the stacktop
: retrieves the element at the top without removing it
stack<int> s;s.push(1); // [1]s.push(13); // [1, 13]s.push(7); // [1, 13, 7]cout << s.top() << endl; // 7s.pop(); // [1, 13]cout << s.size() << endl; // 2
Application - Nearest Smaller Element
Focus Problem – try your best to solve this problem before continuing!
Consider the following problem:
Given an array, , of () integers, for every index , find the rightmost index such that and .
Resources | ||||
---|---|---|---|---|
CPH | ||||
CSA | similar application w/ animation |
To solve this, let's store a stack of pairs of and iterate over the array from left to right. For some index , we will compute , the rightmost index for , as follows:
- Keep popping the top element off the stack as long as . This is because we know that the pair containing will never be the solution to any index , since is less than or equal to than and has an index further to the right.
- If , set to , because a stack stores the most recently added values first (or in this case, the rightmost ones), will contain the rightmost value which is less than . Then, add () to the stack.
The stack we used is called a monotonic stack because we keep popping off the top element of the stack which maintains it's monotonicity (the same property needed for algorithms like binary search) because the elements in the stack are increasing.
Implementation
#include <bits/stdc++.h>using namespace std;int N;int main() {ios_base::sync_with_stdio(0);cin.tie(0);
Problems
Status | Source | Problem Name | Difficulty | Tags | |
---|---|---|---|---|---|
CSES | Easy | Show TagsStack | |||
CF | Normal | Show TagsStack | |||
CEOI | Normal | Show TagsGeometry, Stack | |||
Baltic OI | Normal | Show TagsBinary Search, Stack | |||
Gold | Normal | Show TagsStack | |||
Gold | Normal | Show TagsBinary Search, Stack | |||
CSES | Normal | Show TagsStack | |||
CEOI | Normal | Show TagsStack | |||
CF | Normal | Show TagsStack | |||
Gold | Hard | Show TagsLinked List, Sorted Set, Stack | |||
CSES | Hard | Show TagsPURS, Stack | |||
CF | Hard | Show TagsDP, PURS, Stack | |||
IOI | Very Hard | Show TagsStack | |||
Kilonova | Very Hard | Show TagsStack | |||
CSES | Insane | Show TagsStack | |||
COI | Insane | Show TagsStack |
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!