sotanishy's competitive programming library

sotanishy's code snippets for competitive programming

View the Project on GitHub sotanishy/cp-library-cpp

:warning: Persistent Stack
(data-structure/persistent_stack.hpp)

Description

永続スタックは,過去のバージョンを保持するスタックである.

空間計算量: $O(m)$, $m$ は変更の数

Operations

Reference

Code

#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) {}
};
Back to top page