sotanishy's code snippets for competitive programming
#include "data-structure/persistent_stack.hpp"
永続スタックは,過去のバージョンを保持するスタックである.
空間計算量: $O(m)$, $m$ は変更の数
bool empty()
T top()
PersistentStack push(T val)
val
を先頭に追加するPersistentStack pop()
#pragma once
#include <memory>
template <typename T>
class PersistentStack {
public:
PersistentStack() = default;
T top() const { return last->val; }
bool empty() const { return last == nullptr; }
PersistentStack push(const T& val) const {
return PersistentStack(std::make_shared<Node>(val, last));
}
PersistentStack pop() const { return PersistentStack(last->prev); }
private:
struct Node;
using node_ptr = std::shared_ptr<Node>;
struct Node {
T val;
node_ptr prev;
Node(T val, node_ptr prev) : val(val), prev(prev) {}
};
node_ptr last;
explicit PersistentStack(node_ptr last) : last(last) {}
};
#line 2 "data-structure/persistent_stack.hpp"
#include <memory>
template <typename T>
class PersistentStack {
public:
PersistentStack() = default;
T top() const { return last->val; }
bool empty() const { return last == nullptr; }
PersistentStack push(const T& val) const {
return PersistentStack(std::make_shared<Node>(val, last));
}
PersistentStack pop() const { return PersistentStack(last->prev); }
private:
struct Node;
using node_ptr = std::shared_ptr<Node>;
struct Node {
T val;
node_ptr prev;
Node(T val, node_ptr prev) : val(val), prev(prev) {}
};
node_ptr last;
explicit PersistentStack(node_ptr last) : last(last) {}
};