結果

問題 No.3319 Iwaijkstra
コンテスト
ユーザー hitonanode
提出日時 2025-11-01 14:11:32
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 25,602 bytes
コンパイル時間 6,256 ms
コンパイル使用メモリ 301,448 KB
実行使用メモリ 119,888 KB
最終ジャッジ日時 2025-11-01 14:12:14
合計ジャッジ時間 34,887 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 20 WA * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
const std::vector<std::pair<int, int>> grid_dxs{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <class T1, class T2> T1 floor_div(T1 num, T2 den) { return (num > 0 ? num / den : -((-num + den - 1) / den)); }
template <class T1, class T2> std::pair<T1, T2> operator+(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first + r.first, l.second + r.second); }
template <class T1, class T2> std::pair<T1, T2> operator-(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first - r.first, l.second - r.second); }
template <class T> std::vector<T> sort_unique(std::vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <class T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <class T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <class IStream, class T> IStream &operator>>(IStream &is, std::vector<T> &vec) { for (auto &v : vec) is >> v; return is; }

template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec);
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr);
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const pair<T, U> &pa);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa);
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp);
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp);
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl);

template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
template <class... T> std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; }
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl
#define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl : std::cerr)
#else
#define dbg(x) ((void)0)
#define dbgif(cond, x) ((void)0)
#endif

#include <atcoder/scc>


#include <algorithm>
#include <vector>

// Enumerate nodes of nonrecursive segtree which cover [l, r)
std::vector<int> segtree_range_covering_nodes(int N, int l, int r) {
    std::vector<int> ret, ret_rev;
    l += N, r += N;
    while (l < r) {
        if (l & 1) ret.push_back(l++);
        if (r & 1) ret_rev.push_back(--r);
        l >>= 1, r >>= 1;
    }
    std::reverse(ret_rev.begin(), ret_rev.end());
    ret.insert(ret.end(), ret_rev.begin(), ret_rev.end());
    return ret;
}

constexpr lint inf = 1000000000000000001;

// 0-indexed BIT (binary indexed tree / Fenwick tree) (i : [0, len))
template <class T> struct BIT {
    int n;
    std::vector<T> data;
    BIT(int len = 0) : n(len), data(len) {}
    void reset() { std::fill(data.begin(), data.end(), T(0)); }
    void add(int pos, T v) { // a[pos] += v
        pos++;
        while (pos > 0 and pos <= n) data[pos - 1] += v, pos += pos & -pos;
    }
    T sum(int k) const { // a[0] + ... + a[k - 1]
        T res = 0;
        while (k > 0) res += data[k - 1], k -= k & -k;
        return res;
    }

    T sum(int l, int r) const { return sum(r) - sum(l); } // a[l] + ... + a[r - 1]

    template <class OStream> friend OStream &operator<<(OStream &os, const BIT &bit) {
        T prv = 0;
        os << '[';
        for (int i = 1; i <= bit.n; i++) {
            T now = bit.sum(i);
            os << now - prv << ',', prv = now;
        }
        return os << ']';
    }
};


#include <cassert>
#include <cstdint>
#include <vector>

// Sorted set of integers [0, n)
// Space complexity: (64 / 63) n + O(log n) bit
class fast_set {
    static constexpr int B = 64;

    int n;
    int cnt;
    std::vector<std::vector<uint64_t>> _d;

    static int bsf(uint64_t x) { return __builtin_ctzll(x); }
    static int bsr(uint64_t x) { return 63 - __builtin_clzll(x); }

public:
    // 0 以上 n_ 未満の整数が入れられる sorted set を作成
    fast_set(int n_) : n(n_), cnt(0) {
        do { n_ = (n_ + B - 1) / B, _d.push_back(std::vector<uint64_t>(n_)); } while (n_ > 1);
    }

    bool contains(int i) const {
        assert(0 <= i and i < n);
        return (_d.front().at(i / B) >> (i % B)) & 1;
    }

    void insert(int i) {
        assert(0 <= i and i < n);
        if (contains(i)) return;
        ++cnt;
        for (auto &vec : _d) {
            bool f = vec.at(i / B);
            vec.at(i / B) |= 1ULL << (i % B), i /= B;
            if (f) break;
        }
    }

    void erase(int i) {
        assert(0 <= i and i < n);
        if (!contains(i)) return;
        --cnt;
        for (auto &vec : _d) {
            vec.at(i / B) &= ~(1ULL << (i % B)), i /= B;
            if (vec.at(i)) break;
        }
    }

    // i 以上の最小要素 なければ default_val
    int next(int i, const int default_val) const {
        assert(0 <= i and i <= n);

        for (auto itr = _d.cbegin(); itr != _d.cend(); ++itr, i = i / B + 1) {
            if (i / B >= int(itr->size())) break;

            if (auto d = itr->at(i / B) >> (i % B); d) {
                i += bsf(d);
                while (itr != _d.cbegin()) i = i * B + bsf((--itr)->at(i));
                return i;
            }
        }

        return default_val;
    }
    int next(const int i) const { return next(i, n); }

    // i 以下の最小要素 なければ default_val
    int prev(int i, int default_val = -1) const {
        assert(-1 <= i and i < n);

        for (auto itr = _d.cbegin(); itr != _d.cend() and i >= 0; ++itr, i = i / B - 1) {
            if (auto d = itr->at(i / B) << (B - 1 - i % B); d) {
                i += bsr(d) - (B - 1);
                while (itr != _d.cbegin()) i = i * B + bsr((--itr)->at(i));
                return i;
            }
        }

        return default_val;
    }

    // return minimum element (if exists) or `n` (empty)
    int min() const { return next(0); }
    // return maximum element (if exists) or `-1` (empty)
    int max() const { return prev(n - 1); }
    int size() const { return cnt; }
    bool empty() const { return cnt == 0; }

    void clear() {
        if (!cnt) return;
        cnt = 0;
        auto rec = [&](auto &&self, int d, int x) -> void {
            if (d) {
                for (auto m = _d.at(d).at(x); m;) {
                    int i = bsf(m);
                    m -= 1ULL << i, self(self, d - 1, x * B + i);
                }
            }
            _d.at(d).at(x) = 0;
        };
        rec(rec, _d.size() - 1, 0);
    }
};


#include <atcoder/lazysegtree>

using Se = pair<lint, int>;
Se op(Se l, Se r) { return {min(l.first + r.first, inf), l.second + r.second}; }
Se e() { return {0, 0}; }
using F = lint;
Se mapping(F f, Se x) { return {min(x.first + x.second * f, inf), x.second}; }
F composition(F f, F g) { return min(f + g, inf); }
F id() { return 0; }


#include <algorithm>
#include <bit>
#include <cassert>
#include <cstdint>
#include <optional>
#include <vector>

template <class Int> class wavelet_matrix {

    class bit_vector {
        static constexpr int WSIZE = 64;
        int n = 0;
        int cnt0 = 0;
        std::vector<uint64_t> bits;
        std::vector<int> count_cumsum; // need build()

    public:
        bit_vector(int n_) : n(n_), cnt0(n_) {
            assert(n >= 0);
            bits.assign((n + WSIZE - 1) / WSIZE, 0);
        }

        int size() const { return n; }

        void set(int i) {
            assert(0 <= i and i < n);
            bits[i / WSIZE] |= (1ULL << (i % WSIZE));
        }

        void reset(int i) {
            assert(0 <= i and i < n);
            bits[i / WSIZE] &= ~(1ULL << (i % WSIZE));
        }

        void build() {
            cnt0 = n;
            for (int i = 0; i < (int)bits.size(); ++i) cnt0 -= std::popcount(bits[i]);
            count_cumsum.assign(bits.size(), 0);
            for (int i = 1; i < (int)bits.size(); ++i) {
                count_cumsum[i] = count_cumsum[i - 1] + std::popcount(bits[i - 1]);
            }
        }

        int count0() const { return cnt0; }

        int count1() const { return n - cnt0; }

        // get i-th bit
        bool access(int i) const {
            assert(0 <= i and i < n);
            return bits[i / WSIZE] & (1ULL << (i % WSIZE));
        }

        // count of 0s in [0, i)
        int rank0(int i) const {
            assert(0 <= i and i <= n);
            return i - rank1(i);
        }

        // count of 1s in [0, i)
        int rank1(int i) const {
            assert(0 <= i and i <= n);
            if (i == n) return count1();
            return count_cumsum[i / WSIZE] +
                   std::popcount(bits[i / WSIZE] & ((1ULL << (i % WSIZE)) - 1));
        }

        // get the position of i-th element after stable sort
        int sorted_pos(int i) const { return access(i) ? (rank1(i) + count0()) : rank0(i); }

        template <class OStream> friend OStream &operator<<(OStream &os, const bit_vector &bv) {
            os << "bit_vector[" << bv.n << "]: ";
            for (int i = 0; i < bv.n; ++i) {
                os << (bv.bits[i / WSIZE] & (1ULL << (i % WSIZE)) ? '1' : '0');
            }
            os << " (cnt0: " << bv.cnt0 << ")";
            return os;
        }
    };

    std::vector<bit_vector> bits;

    std::vector<std::pair<Int, Int>> points;
    std::vector<Int> distinct_ys;

    int to_index_x(Int x) const {
        return std::lower_bound(points.cbegin(), points.cend(), std::make_pair(x, Int{}),
                                [](const auto &l, const auto &r) { return l.first < r.first; }) -
               points.cbegin();
    }

    int to_index_y(Int y) const {
        return std::lower_bound(distinct_ys.cbegin(), distinct_ys.cend(), y) - distinct_ys.cbegin();
    }

    bool is_built() const { return !bits.empty(); }

public:
    wavelet_matrix() = default;

    wavelet_matrix(const std::vector<Int> &ys) {
        for (int x = 0; x < (int)ys.size(); ++x) {
            assert(ys[x] >= 0);
            add_point(x, ys[x]);
        }
        build();
    }

    void add_point(Int x, Int y) {
        assert(bits.empty()); // confirm that build() is not called yet
        points.emplace_back(x, y);
        distinct_ys.emplace_back(y);
    }

    void build() {
        std::sort(points.begin(), points.end());
        points.erase(std::unique(points.begin(), points.end()), points.end());

        std::sort(distinct_ys.begin(), distinct_ys.end());
        distinct_ys.erase(std::unique(distinct_ys.begin(), distinct_ys.end()), distinct_ys.end());

        int d = 1;
        while ((1 << d) < (int)distinct_ys.size()) ++d;
        bits.assign(d, bit_vector(N()));

        std::vector<int> a;
        for (auto p : points) a.push_back(to_index_y(p.second));
        auto nxt = a;

        for (int d = D() - 1; d >= 0; --d) {
            for (int i = 0; i < N(); ++i) {
                if ((a[i] >> d) & 1) bits[d].set(i);
            }
            bits[d].build();

            for (int i = 0; i < N(); ++i) nxt[bits[d].sorted_pos(i)] = a[i];

            std::swap(a, nxt);
        }
    }

    int N() const { return points.size(); }

    int D() const { return bits.size(); }

    // get v_i
    int index_access(int i) const {
        assert(0 <= i and i < N());
        assert(is_built());

        int ret = 0;
        for (int d = D() - 1; d >= 0; --d) {
            ret |= (int)bits[d].access(i) << d;
            i = bits[d].sorted_pos(i);
        }
        return ret;
    }

    Int access(int i) const {
        assert(0 <= i and i < N());
        assert(is_built());
        return distinct_ys.at(index_access(i));
    }

    // callback(d, i) means "update d-th segment's i-th element"
    void index_apply(int i, auto callback) const {
        assert(0 <= i and i < N());
        assert(is_built());

        for (int d = D() - 1; d >= 0; --d) {
            i = bits[d].sorted_pos(i);
            callback(d, i);
        }
    }

    // Update weight associated to point (x, y)
    // callback(d, i) means "update d-th segment's i-th element"
    void apply(Int x, Int y, auto callback) const {
        const int i = std::lower_bound(points.cbegin(), points.cend(), std::make_pair(x, y)) -
                      points.cbegin();
        assert(i < N() and points[i] == std::make_pair(x, y));
        index_apply(i, callback);
    }

    void index_prod(int l, int r, int yr, auto callback) const {
        assert(0 <= l and l <= r and r <= N());
        assert(0 <= yr and yr <= (int)distinct_ys.size());
        assert(is_built());

        if (yr & (1 << D())) {
            const int d = D() - 1;
            const int l0 = bits[d].rank0(l), r0 = bits[d].rank0(r);
            callback(d, l0, r0);
            const int l1 = bits[d].rank1(l) + bits[d].count0();
            const int r1 = bits[d].rank1(r) + bits[d].count0();
            callback(d, l1, r1);
            return;
        }

        for (int d = D() - 1; d >= 0; --d) {
            if (l == r) break;
            const int l0 = bits[d].rank0(l), r0 = bits[d].rank0(r);
            if ((yr >> d) & 1) {
                callback(d, l0, r0);
                // l = bits[d].rank1(l) + bits[d].count0();
                l += bits[d].count0() - l0;
                // r = bits[d].rank1(r) + bits[d].count0();
                r += bits[d].count0() - r0;
            } else {
                l = l0, r = r0;
            }
        }
    }

    // Get product of weights associated to elements in [xl, xr) * [-inf, yr)
    // callback(d, l, r) means "use d-th segment's [l, r) elements"
    void prod(Int xl, Int xr, Int yr, auto callback) const {
        index_prod(to_index_x(xl), to_index_x(xr), to_index_y(yr), callback);
    }

    // Get k-th smallest v_i, i in [l, r) (0-indexed, duplicates are counted)]
    int index_kth_smallest(int l, int r, int k) const {
        assert(0 <= l and l <= r and r <= N());
        assert(0 <= k and k < r - l);
        assert(is_built());

        int ret = 0;
        for (int d = D() - 1; d >= 0; --d) {
            const int l0 = bits[d].rank0(l), r0 = bits[d].rank0(r);
            if (k < r0 - l0) {
                l = l0, r = r0;
            } else {
                k -= r0 - l0;
                ret |= 1 << d;
                l = bits[d].rank1(l) + bits[d].count0();
                r = bits[d].rank1(r) + bits[d].count0();
            }
        }

        return ret;
    }

    // Get k-th largest v_i, i in [l, r) (0-indexed, duplicates are counted)
    int index_kth_largest(int l, int r, int k) const {
        assert(0 <= l and l <= r and r <= N());
        assert(0 <= k and k < r - l);
        return index_kth_smallest(l, r, (r - l - 1) - k);
    }

    // count i s.t. i in [l, r) and v_i < upper_bound
    int index_range_freq(int l, int r, int upper_bound) const {
        assert(0 <= l and l <= r and r <= N());
        assert(is_built());
        if (upper_bound <= 0) return 0;
        if (upper_bound >= (int)distinct_ys.size()) return r - l;

        int ret = 0;
        for (int d = D() - 1; d >= 0; --d) {
            const int l0 = bits[d].rank0(l), r0 = bits[d].rank0(r);
            if ((upper_bound >> d) & 1) {
                ret += r0 - l0;
                l = bits[d].rank1(l) + bits[d].count0();
                r = bits[d].rank1(r) + bits[d].count0();
            } else {
                l = l0, r = r0;
            }
        }

        return ret;
    }

    // Get k-th smallest y in [xl, xr) (0-indexed, duplicates are counted)
    std::optional<Int> kth_smallest(Int xl, Int xr, int k) const {
        const int l = to_index_x(xl), r = to_index_x(xr);
        if (k < 0 or k >= r - l) return std::nullopt;
        return distinct_ys.at(index_kth_smallest(l, r, k));
    }

    // Get k-th largest y in [xl, xr) (0-indexed, duplicates are counted)
    std::optional<Int> kth_largest(Int xl, Int xr, int k) const {
        const int l = to_index_x(xl), r = to_index_x(xr);
        if (k < 0 or k >= r - l) return std::nullopt;
        return distinct_ys.at(index_kth_largest(l, r, k));
    }

    // count points in [xl, xr) * [-inf, yr)
    int range_freq(Int xl, Int xr, Int yr) const {
        return index_range_freq(to_index_x(xl), to_index_x(xr), to_index_y(yr));
    }

    // max v_i s.t. i in [l, r), v_i < upper_bound
    std::optional<int> index_prev_value(int l, int r, int upper_bound) const {
        assert(0 <= l and l <= r and r <= N());
        assert(is_built());
        if (upper_bound <= 0) return std::nullopt;

        const int n = index_range_freq(l, r, upper_bound);
        return n == 0 ? std::nullopt : index_kth_smallest(l, r, n - 1);
    }

    // max y s.t. x in [xl, xr), y < yr
    std::optional<Int> prev_value(Int xl, Int xr, Int yr) const {
        const int l = to_index_x(xl), r = to_index_x(xr), ub = to_index_y(yr);
        const auto idx = index_prev_value(l, r, ub);
        return idx ? distinct_ys.at(*idx) : std::nullopt;
    }

    // min v_i s.t. i in [l, r), v_i >= lower_bound
    std::optional<int> index_next_value(int l, int r, int lower_bound) const {
        assert(0 <= l and l <= r and r <= N());
        assert(is_built());
        if (lower_bound >= (int)distinct_ys.size()) return std::nullopt;
        const int n = index_range_freq(l, r, lower_bound);
        return n >= (r - l) ? std::nullopt : index_kth_smallest(l, r, n);
    }

    // min y s.t. x in [xl, xr), y >= yl
    std::optional<Int> next_value(Int l, Int r, Int yl) const {
        const int xl = to_index_x(l), xr = to_index_x(r), yl_idx = to_index_y(yl);
        const auto idx = index_next_value(xl, xr, yl_idx);
        return idx ? distinct_ys.at(*idx) : std::nullopt;
    }
};
/* Sample usage:
wavelet_matrix<int> wm;

wm.build();
vector tmp(wm.D(), BIT<T>(wm.N()));
wm.apply(i, j, [&](int d, int idx) { tmp[d].add(idx, wx); });  // point add
T ret{};
wm.prod(l, r, u, [&](int d, int l0, int r0) { ret += tmp[d].sum(l0, r0); }); // range sum
*/


int main() {
    int N, M;
    cin >> N >> M;

    int S = 1;
    while (S < N) S *= 2;
    vector<vector<pair<int, lint>>> seg_to(S + N);
    atcoder::scc_graph cycle(S + N);
    FOR(i, 1, S) {
        if (i * 2 < S + N) {
            seg_to.at(i).emplace_back(i * 2, 0);
            cycle.add_edge(i, i * 2);
        }
        if (i * 2 + 1 < S + N) {
            seg_to.at(i).emplace_back(i * 2 + 1, 0);
            cycle.add_edge(i, i * 2 + 1);
        }
    }

    vector<vector<tuple<int, int, lint>>> to(N);
    lint ret = 0;

    REP(e, M) {
        int x, l, r;
        lint c;
        cin >> x >> l >> r >> c;
        --x;
        --l;
        to.at(x).emplace_back(l, r, c);
        if (l <= x and x < r and c == 0) ret = inf;
        for (auto v : segtree_range_covering_nodes(S, l, r)) {
            seg_to.at(S + x).emplace_back(v, c);
            if (c == 0) cycle.add_edge(S + x, v);
        }
    }

    vector<lint> min_dist(S + N, inf);

    min_dist.at(S) = 0;

    priority_queue<plint, vector<plint>, greater<>> pq;
    pq.emplace(0, S);

    using Seg = atcoder::lazy_segtree<Se, op, e, F, mapping, composition, id>;

    vector<int> ord;

    while (!pq.empty()) {
        auto [dnow, now] = pq.top();
        pq.pop();
        if (dnow != min_dist.at(now)) continue;
        if (now >= S) ord.push_back(now - S);

        for (auto [nxt, w] : seg_to.at(now)) {
            if (chmin(min_dist.at(nxt), min_dist.at(now) + w)) pq.emplace(min_dist.at(nxt), nxt);
        }
    }

    assert((int)ord.size() == N);

    min_dist = vector<lint>{min_dist.begin() + S, min_dist.begin() + S + N};

    wavelet_matrix<lint> wm(min_dist);

    vector<Se> init(N, {0, 1});

    vector tmp(wm.D(), Seg(init));

    wm.apply(0, 0, [&](int d, int pos) { tmp[d].apply(pos, 1); });

    Seg seg(init);
    seg.set(0, {1, 1});

    vector<lint> all_access(N);
    vector<lint> shortest_access(N);

    fast_set visited(N);

    if ((int)cycle.scc().size() < S + N) ret = inf;

    lint last_dist = -1;

    BIT<int> bibi(N);

    for (auto i : ord) {
        if (const lint d = min_dist.at(i); d != last_dist) {
            for (int i = visited.next(0); i < N; i = visited.next(i)) {
                visited.erase(i);
                bibi.add(i, -1);
            }
            last_dist = d;
        }

        wm.prod(i, i + 1, min_dist.at(i) + 1, [&](int d, int l, int r) {
            shortest_access[i] += tmp[d].prod(l, r).first;
            chmin(shortest_access.at(i), inf);
        });

        all_access.at(i) = seg.get(i).first;

        visited.insert(i);
        bibi.add(i, 1);
        for (auto [l, r, weight] : to.at(i)) {
            if (weight) ret += bibi.sum(l, r);

            seg.apply(l, r, shortest_access.at(i));
            wm.prod(l, r, min_dist.at(i) + weight + 1,
                    [&](int d, int l, int r) { tmp[d].apply(l, r, shortest_access.at(i)); });
        }
    }

    for (auto x : all_access) {
        ret += x;
        chmin(ret, inf);
    }

    if (ret < inf) {
        cout << ret << '\n';
    } else {
        puts("Too Many");
    }
}
0