Problem:
Problem G:
Concert Hall Scheduling
You are appointed director of a famous concert hall, to save it from bankruptcy. The hall is very
popular, and receives many requests to use its two fine rooms, but unfortunately the previous
director was not very efficient, and it has been losing money for many years. The two rooms are
of the same size and arrangement. Therefore, each applicant wishing to hold a concert asks for
a room without specifying which. Each room can be used for only one concert per day.
In order to make more money, you have decided to abandon the previous fixed price policy, and
rather let applicants specify the price they are ready to pay. Each application shall specify a
period [
i
,
j
] and an asking price
w
, where
i
and
j
are respectively the first and last days of the
period (1 ≤
i
≤
j
≤ 365), and
w
is a positive integer in yen, indicating the amount the applicant
is willing to pay to use a room for the whole period.
You have received applications for the next year, and you should now choose the applications
you will accept. Each application should be either accepted for its whole period or completely
rejected. Each concert should use the same room during the whole applied period.
Considering the dire economic situation of the concert hall, artistic quality is to be ignored,
and you should just try to maximize the total income for the whole year by accepting the most
profitable applications.
Input
The input has multiple data sets, each starting with a line consisting of a single integer n, the
number of applications in the data set. Then, it is followed by
n
lines, each of which represents
one application with a period [
i
,
j
] and an asking price
w
yen in the following format.
i j w
A line containing a single zero indicates the end of the input.
The maximum number of applications in a data set is one thousand, and the maximum asking
price is one million yen.
Output
For each data set, print a single line containing an integer, the maximum total income in yen
for the data set.
Sample Input
4
1 2 10
2 3 10
3 3 10
1 3 10
6
1 20 1000
3 25 10000
5 15 5000
22 300 5500
10 295 9000
7 7 6000
8
32 251 2261
123 281 1339
211 235 5641
162 217 7273
22 139 7851
194 198 9190
119 274 878
122 173 8640
0
Output for the Sample Input
30
25500
38595

Submitted solutions:

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
while(1) {
    int K = 365;
    int N;
    cin >> N;
    if (N == 0) return 0;
    vector<int> L(N), R(N), C(N);
    rep(i,0,N) cin >> L[i] >> R[i] >> C[i], L[i]--;
    vector<int> ord(N);
    iota(ALL(ord),0);
    sort(ALL(ord),[&](int i, int j){return R[i]<R[j];});
    vector<vector<int>> DP(K+1,vector<int>(K+1,0));
    for (int i : ord) {
        vector<vector<int>> NewDP(K+1,vector<int>(K+1,0));
        rep(j,0,K+1) chmax(NewDP[j][R[i]],DP[j][L[i]]+C[i]);
        rep(j,0,K+1) chmax(NewDP[R[i]][j],DP[L[i]][j]+C[i]);
        rep(j,0,K+1) rep(k,0,K+1) chmax(DP[j][k],NewDP[j][k]);
        rep(j,0,K+1) {
            rep(k,0,K+1) {
                if (j+1<=K) chmax(DP[j+1][k],DP[j][k]);
                if (k+1<=K) chmax(DP[j][k+1],DP[j][k]);
            }
        }
    }
    cout << DP[K][K] << endl;
}
}
accuracy: 1
time_ms: 990
memory_kb: 4148
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;

void solve(int N) {
    vector<pair<pair<ll,ll>,ll>> P(N);
    for(int i=0;i<N;i++)cin>>P[i].first.first>>P[i].first.second>>P[i].second;
    sort(P.begin(),P.end());
    vector<vector<ll>> DP(366,vector<ll>(366,0));
    for(int i=0;i<N;i++){
        auto NDP=DP;
        auto [L,R]=P[i].first;
        for(int n=0;n<=365;n++){
            for(int j=0;j<=365;j++){
                if(n<L){
                    DP[R][j]=max(DP[R][j],NDP[n][j]+P[i].second);
                }
                if(j<L){
                    DP[n][R]=max(DP[n][R],NDP[n][j]+P[i].second);
                }
            }
        }
        for(int n=0;n<=365;n++){
            for(int j=0;j<=365;j++){
                if(n!=365)DP[n+1][j]=max(DP[n+1][j],DP[n][j]);
                if(j!=365)DP[n][j+1]=max(DP[n][j+1],DP[n][j]);
            }
        }
    }
    cout<<DP[365][365]<<endl;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int T;
    while (cin>>T,T!=0)solve(T);
}
accuracy: 1
time_ms: 1880
memory_kb: 5272
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;

#ifdef _RUTHEN
#include "debug.hpp"
#else
#define show(...) true
#endif

using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
template <class T> using V = vector<T>;

void solve(int N) {
    V<tuple<int, int, int>> LRW(N);
    rep(i, N) {
        int l, r, w;
        cin >> l >> r >> w;
        l--;
        LRW[i] = {l, r, w};
    }
    sort(LRW.begin(), LRW.end());
    int M = 365;
    V<V<ll>> dp(M + 1, V<ll>(M + 1, 0));
    // 蟻本p221のグラフを2次元に拡張し、DAGの最長路を計算
    // ->これだと同じ区間を2回使ってしまう(例えばsample1で[1,2][3,3]を2回ずつ使って40など)
    // ->3次元に拡張
    // 同一の高さでは平面的な遷移(np[i1 + 1][i2] = max(np[i1 + 1][i2], np[i1][i2])など)
    // 高さが+1するところで区間を使った遷移をする(これによって同じ区間を使うことはなくなる)
    // このとき、解を復元することを考えると、区間は始点ソートしておけば、解として選ばれた任意の同一ホールでの区間について
    // 後日の区間がより前の日の区間より先に来ることはないので、最適解を求められる
    rep(i, N) {
        auto [l, r, w] = LRW[i];
        V<V<ll>> np = dp;
        rep(i1, M + 1) {
            rep(i2, M + 1) {
                if (i1 == l) {
                    np[r][i2] = max(np[r][i2], dp[i1][i2] + w);
                }
                if (i2 == l) {
                    np[i1][r] = max(np[i1][r], dp[i1][i2] + w);
                }
                if (i1 + 1 <= M) np[i1 + 1][i2] = max(np[i1 + 1][i2], np[i1][i2]);
                if (i2 + 1 <= M) np[i1][i2 + 1] = max(np[i1][i2 + 1], np[i1][i2]);
            }
        }
        dp = np;
    }
    cout << dp[M][M] << '\n';
    return;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    while (cin >> N, N != 0) solve(N);
    return 0;
}
accuracy: 1
time_ms: 1590
memory_kb: 5156
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;

#ifdef _RUTHEN
#include "debug.hpp"
#else
#define show(...) true
#endif

using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
template <class T> using V = vector<T>;

void solve(int N) {
    V<tuple<int, int, int>> LRW(N);
    rep(i, N) {
        int l, r, w;
        cin >> l >> r >> w;
        l--;
        LRW[i] = {l, r, w};
    }
    sort(LRW.begin(), LRW.end());
    show(LRW);
    int M = 365;
    V<V<ll>> dp(M + 1, V<ll>(M + 1, 0));
    rep(i, N) {
        auto [l, r, w] = LRW[i];
        V<V<ll>> np = dp;
        rep(i1, M + 1) {
            rep(i2, M + 1) {
                if (i1 == l) {
                    np[r][i2] = max(np[r][i2], dp[i1][i2] + w);
                }
                if (i2 == l) {
                    np[i1][r] = max(np[i1][r], dp[i1][i2] + w);
                }
                if (i1 + 1 <= M) np[i1 + 1][i2] = max(np[i1 + 1][i2], np[i1][i2]);
                if (i2 + 1 <= M) np[i1][i2 + 1] = max(np[i1][i2 + 1], np[i1][i2]);
            }
        }
        dp = np;
    }
    cout << dp[M][M] << '\n';
    return;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    while (cin >> N, N != 0) solve(N);
    return 0;
}
accuracy: 1
time_ms: 1610
memory_kb: 5120
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;

#ifdef _RUTHEN
#include "debug.hpp"
#else
#define show(...) true
#endif

using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
template <class T> using V = vector<T>;


#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>


#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    explicit csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

}  // namespace internal

}  // namespace atcoder


#include <vector>

namespace atcoder {

namespace internal {

template <class T> struct simple_queue {
    std::vector<T> payload;
    int pos = 0;
    void reserve(int n) { payload.reserve(n); }
    int size() const { return int(payload.size()) - pos; }
    bool empty() const { return pos == int(payload.size()); }
    void push(const T& t) { payload.push_back(t); }
    T& front() { return payload[pos]; }
    void clear() {
        payload.clear();
        pos = 0;
    }
    void pop() { pos++; }
};

}  // namespace internal

}  // namespace atcoder


namespace atcoder {

template <class Cap, class Cost> struct mcf_graph {
  public:
    mcf_graph() {}
    explicit mcf_graph(int n) : _n(n) {}

    int add_edge(int from, int to, Cap cap, Cost cost) {
        assert(0 <= from && from < _n);
        assert(0 <= to && to < _n);
        assert(0 <= cap);
        assert(0 <= cost);
        int m = int(_edges.size());
        _edges.push_back({from, to, cap, 0, cost});
        return m;
    }

    struct edge {
        int from, to;
        Cap cap, flow;
        Cost cost;
    };

    edge get_edge(int i) {
        int m = int(_edges.size());
        assert(0 <= i && i < m);
        return _edges[i];
    }
    std::vector<edge> edges() { return _edges; }

    std::pair<Cap, Cost> flow(int s, int t) {
        return flow(s, t, std::numeric_limits<Cap>::max());
    }
    std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
        return slope(s, t, flow_limit).back();
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
        return slope(s, t, std::numeric_limits<Cap>::max());
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
        assert(0 <= s && s < _n);
        assert(0 <= t && t < _n);
        assert(s != t);

        int m = int(_edges.size());
        std::vector<int> edge_idx(m);

        auto g = [&]() {
            std::vector<int> degree(_n), redge_idx(m);
            std::vector<std::pair<int, _edge>> elist;
            elist.reserve(2 * m);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] = degree[e.from]++;
                redge_idx[i] = degree[e.to]++;
                elist.push_back({e.from, {e.to, -1, e.cap - e.flow, e.cost}});
                elist.push_back({e.to, {e.from, -1, e.flow, -e.cost}});
            }
            auto _g = internal::csr<_edge>(_n, elist);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] += _g.start[e.from];
                redge_idx[i] += _g.start[e.to];
                _g.elist[edge_idx[i]].rev = redge_idx[i];
                _g.elist[redge_idx[i]].rev = edge_idx[i];
            }
            return _g;
        }();

        auto result = slope(g, s, t, flow_limit);

        for (int i = 0; i < m; i++) {
            auto e = g.elist[edge_idx[i]];
            _edges[i].flow = _edges[i].cap - e.cap;
        }

        return result;
    }

  private:
    int _n;
    std::vector<edge> _edges;

    struct _edge {
        int to, rev;
        Cap cap;
        Cost cost;
    };

    std::vector<std::pair<Cap, Cost>> slope(internal::csr<_edge>& g,
                                            int s,
                                            int t,
                                            Cap flow_limit) {

        std::vector<std::pair<Cost, Cost>> dual_dist(_n);
        std::vector<int> prev_e(_n);
        std::vector<bool> vis(_n);
        struct Q {
            Cost key;
            int to;
            bool operator<(Q r) const { return key > r.key; }
        };
        std::vector<int> que_min;
        std::vector<Q> que;
        auto dual_ref = [&]() {
            for (int i = 0; i < _n; i++) {
                dual_dist[i].second = std::numeric_limits<Cost>::max();
            }
            std::fill(vis.begin(), vis.end(), false);
            que_min.clear();
            que.clear();

            size_t heap_r = 0;

            dual_dist[s].second = 0;
            que_min.push_back(s);
            while (!que_min.empty() || !que.empty()) {
                int v;
                if (!que_min.empty()) {
                    v = que_min.back();
                    que_min.pop_back();
                } else {
                    while (heap_r < que.size()) {
                        heap_r++;
                        std::push_heap(que.begin(), que.begin() + heap_r);
                    }
                    v = que.front().to;
                    std::pop_heap(que.begin(), que.end());
                    que.pop_back();
                    heap_r--;
                }
                if (vis[v]) continue;
                vis[v] = true;
                if (v == t) break;
                Cost dual_v = dual_dist[v].first, dist_v = dual_dist[v].second;
                for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                    auto e = g.elist[i];
                    if (!e.cap) continue;
                    Cost cost = e.cost - dual_dist[e.to].first + dual_v;
                    if (dual_dist[e.to].second - dist_v > cost) {
                        Cost dist_to = dist_v + cost;
                        dual_dist[e.to].second = dist_to;
                        prev_e[e.to] = e.rev;
                        if (dist_to == dist_v) {
                            que_min.push_back(e.to);
                        } else {
                            que.push_back(Q{dist_to, e.to});
                        }
                    }
                }
            }
            if (!vis[t]) {
                return false;
            }

            for (int v = 0; v < _n; v++) {
                if (!vis[v]) continue;
                dual_dist[v].first -= dual_dist[t].second - dual_dist[v].second;
            }
            return true;
        };
        Cap flow = 0;
        Cost cost = 0, prev_cost_per_flow = -1;
        std::vector<std::pair<Cap, Cost>> result = {{Cap(0), Cost(0)}};
        while (flow < flow_limit) {
            if (!dual_ref()) break;
            Cap c = flow_limit - flow;
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                c = std::min(c, g.elist[g.elist[prev_e[v]].rev].cap);
            }
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                auto& e = g.elist[prev_e[v]];
                e.cap += c;
                g.elist[e.rev].cap -= c;
            }
            Cost d = -dual_dist[s].first;
            flow += c;
            cost += c * d;
            if (prev_cost_per_flow == d) {
                result.pop_back();
            }
            result.push_back({flow, cost});
            prev_cost_per_flow = d;
        }
        return result;
    }
};

}  // namespace atcoder

using namespace atcoder;

void solve(int N) {
    V<int> L(N), R(N), W(N);
    rep(i, N) {
        cin >> L[i] >> R[i] >> W[i];
        L[i]--;
    }
    int K = 2;
    int M = 366;
    mcf_graph<int, ll> G(M + 2);
    ll res = 0;
    int s = M, t = s + 1;
    G.add_edge(s, 0, K, 0);
    G.add_edge(M - 1, t, K, 0);
    rep(i, M - 1) G.add_edge(i, i + 1, K, 0);
    rep(i, N) {
        G.add_edge(R[i], L[i], 1, W[i]);
        G.add_edge(s, R[i], 1, 0);
        G.add_edge(L[i], t, 1, 0);
        res -= W[i];
    }
    res += G.flow(s, t, K + N).second;
    cout << -res << '\n';
    return;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    while (cin >> N, N != 0) solve(N);
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3628
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;

#ifdef _RUTHEN
#include "debug.hpp"
#else
#define show(...) true
#endif

using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
template <class T> using V = vector<T>;


#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>


#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    explicit csr(int n, const std::vector<std::pair<int, E>>& edges)
        : start(n + 1), elist(edges.size()) {
        for (auto e : edges) {
            start[e.first + 1]++;
        }
        for (int i = 1; i <= n; i++) {
            start[i] += start[i - 1];
        }
        auto counter = start;
        for (auto e : edges) {
            elist[counter[e.first]++] = e.second;
        }
    }
};

}  // namespace internal

}  // namespace atcoder


#include <vector>

namespace atcoder {

namespace internal {

template <class T> struct simple_queue {
    std::vector<T> payload;
    int pos = 0;
    void reserve(int n) { payload.reserve(n); }
    int size() const { return int(payload.size()) - pos; }
    bool empty() const { return pos == int(payload.size()); }
    void push(const T& t) { payload.push_back(t); }
    T& front() { return payload[pos]; }
    void clear() {
        payload.clear();
        pos = 0;
    }
    void pop() { pos++; }
};

}  // namespace internal

}  // namespace atcoder


namespace atcoder {

template <class Cap, class Cost> struct mcf_graph {
  public:
    mcf_graph() {}
    explicit mcf_graph(int n) : _n(n) {}

    int add_edge(int from, int to, Cap cap, Cost cost) {
        assert(0 <= from && from < _n);
        assert(0 <= to && to < _n);
        assert(0 <= cap);
        assert(0 <= cost);
        int m = int(_edges.size());
        _edges.push_back({from, to, cap, 0, cost});
        return m;
    }

    struct edge {
        int from, to;
        Cap cap, flow;
        Cost cost;
    };

    edge get_edge(int i) {
        int m = int(_edges.size());
        assert(0 <= i && i < m);
        return _edges[i];
    }
    std::vector<edge> edges() { return _edges; }

    std::pair<Cap, Cost> flow(int s, int t) {
        return flow(s, t, std::numeric_limits<Cap>::max());
    }
    std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
        return slope(s, t, flow_limit).back();
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
        return slope(s, t, std::numeric_limits<Cap>::max());
    }
    std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
        assert(0 <= s && s < _n);
        assert(0 <= t && t < _n);
        assert(s != t);

        int m = int(_edges.size());
        std::vector<int> edge_idx(m);

        auto g = [&]() {
            std::vector<int> degree(_n), redge_idx(m);
            std::vector<std::pair<int, _edge>> elist;
            elist.reserve(2 * m);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] = degree[e.from]++;
                redge_idx[i] = degree[e.to]++;
                elist.push_back({e.from, {e.to, -1, e.cap - e.flow, e.cost}});
                elist.push_back({e.to, {e.from, -1, e.flow, -e.cost}});
            }
            auto _g = internal::csr<_edge>(_n, elist);
            for (int i = 0; i < m; i++) {
                auto e = _edges[i];
                edge_idx[i] += _g.start[e.from];
                redge_idx[i] += _g.start[e.to];
                _g.elist[edge_idx[i]].rev = redge_idx[i];
                _g.elist[redge_idx[i]].rev = edge_idx[i];
            }
            return _g;
        }();

        auto result = slope(g, s, t, flow_limit);

        for (int i = 0; i < m; i++) {
            auto e = g.elist[edge_idx[i]];
            _edges[i].flow = _edges[i].cap - e.cap;
        }

        return result;
    }

  private:
    int _n;
    std::vector<edge> _edges;

    struct _edge {
        int to, rev;
        Cap cap;
        Cost cost;
    };

    std::vector<std::pair<Cap, Cost>> slope(internal::csr<_edge>& g,
                                            int s,
                                            int t,
                                            Cap flow_limit) {

        std::vector<std::pair<Cost, Cost>> dual_dist(_n);
        std::vector<int> prev_e(_n);
        std::vector<bool> vis(_n);
        struct Q {
            Cost key;
            int to;
            bool operator<(Q r) const { return key > r.key; }
        };
        std::vector<int> que_min;
        std::vector<Q> que;
        auto dual_ref = [&]() {
            for (int i = 0; i < _n; i++) {
                dual_dist[i].second = std::numeric_limits<Cost>::max();
            }
            std::fill(vis.begin(), vis.end(), false);
            que_min.clear();
            que.clear();

            size_t heap_r = 0;

            dual_dist[s].second = 0;
            que_min.push_back(s);
            while (!que_min.empty() || !que.empty()) {
                int v;
                if (!que_min.empty()) {
                    v = que_min.back();
                    que_min.pop_back();
                } else {
                    while (heap_r < que.size()) {
                        heap_r++;
                        std::push_heap(que.begin(), que.begin() + heap_r);
                    }
                    v = que.front().to;
                    std::pop_heap(que.begin(), que.end());
                    que.pop_back();
                    heap_r--;
                }
                if (vis[v]) continue;
                vis[v] = true;
                if (v == t) break;
                Cost dual_v = dual_dist[v].first, dist_v = dual_dist[v].second;
                for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                    auto e = g.elist[i];
                    if (!e.cap) continue;
                    Cost cost = e.cost - dual_dist[e.to].first + dual_v;
                    if (dual_dist[e.to].second - dist_v > cost) {
                        Cost dist_to = dist_v + cost;
                        dual_dist[e.to].second = dist_to;
                        prev_e[e.to] = e.rev;
                        if (dist_to == dist_v) {
                            que_min.push_back(e.to);
                        } else {
                            que.push_back(Q{dist_to, e.to});
                        }
                    }
                }
            }
            if (!vis[t]) {
                return false;
            }

            for (int v = 0; v < _n; v++) {
                if (!vis[v]) continue;
                dual_dist[v].first -= dual_dist[t].second - dual_dist[v].second;
            }
            return true;
        };
        Cap flow = 0;
        Cost cost = 0, prev_cost_per_flow = -1;
        std::vector<std::pair<Cap, Cost>> result = {{Cap(0), Cost(0)}};
        while (flow < flow_limit) {
            if (!dual_ref()) break;
            Cap c = flow_limit - flow;
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                c = std::min(c, g.elist[g.elist[prev_e[v]].rev].cap);
            }
            for (int v = t; v != s; v = g.elist[prev_e[v]].to) {
                auto& e = g.elist[prev_e[v]];
                e.cap += c;
                g.elist[e.rev].cap -= c;
            }
            Cost d = -dual_dist[s].first;
            flow += c;
            cost += c * d;
            if (prev_cost_per_flow == d) {
                result.pop_back();
            }
            result.push_back({flow, cost});
            prev_cost_per_flow = d;
        }
        return result;
    }
};

}  // namespace atcoder

using namespace atcoder;

void solve(int N) {
    V<int> L(N), R(N), W(N);
    rep(i, N) {
        cin >> L[i] >> R[i] >> W[i];
        L[i]--;
    }
    int K = 2;
    int M = 366;
    mcf_graph<int, ll> G(M + 2);
    ll res = 0;
    int s = M, t = s + 1;
    G.add_edge(s, 0, 2, 0);
    G.add_edge(M - 1, t, 2, 0);
    rep(i, M - 1) G.add_edge(i, i + 1, 2, 0);
    rep(i, N) {
        G.add_edge(R[i], L[i], 1, W[i]);
        G.add_edge(s, R[i], 1, 0);
        G.add_edge(L[i], t, 1, 0);
        res -= W[i];
    }
    res += G.flow(s, t, K + N).second;
    cout << -res << '\n';
    return;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    while (cin >> N, N != 0) solve(N);
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3696
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
// #pragma GCC target("arch=skylake-avx512")
// #include <atcoder/all>
// using namespace atcoder;
// #define NDEBUG

#pragma region template
// Define
using ll = long long;
using ull = unsigned long long;
using ld = long double;
template <class T> using pvector = vector<pair<T, T>>;
template <class T> using rpriority_queue = priority_queue<T, vector<T>, greater<T>>;
constexpr const ll dx[4] = {1, 0, -1, 0};
constexpr const ll dy[4] = {0, 1, 0, -1};
constexpr const ll MOD = 1e9 + 7;
constexpr const ll mod = 998244353;
constexpr const ll INF = 1LL << 60;
constexpr const ll inf = 1 << 30;
constexpr const char rt = '\n';
constexpr const char sp = ' ';
#define rt(i, n) (i == (ll) (n) -1 ? rt : sp)
#define len(x) ((ll) (x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
#define ifn(x) if (not(x))
#define elif else if
#define elifn else ifn
#define fi first
#define se second
#define uniq(x) (sort(all(x)), (x).erase(unique(all(x)), (x).end()))
#define bis(x, y) ((ll) (lower_bound(all(x), y) - (x).begin()))

using graph = vector<vector<ll>>;
template <class T> using wgraph = vector<vector<pair<ll, T>>>;
bool __DIRECTED__ = true;
bool __ZERO_INDEXED__ = false;
istream &operator>>(istream &is, graph &g) {
    ll a, b;
    is >> a >> b;
    if (__ZERO_INDEXED__ == false) a--, b--;
    g[a].pb(b);
    if (__DIRECTED__ == false) g[b].pb(a);
    return is;
}
template <class T> istream &operator>>(istream &is, wgraph<T> &g) {
    ll a, b;
    T c;
    is >> a >> b >> c;
    if (__ZERO_INDEXED__ == false) a--, b--;
    g[a].pb({b, c});
    if (__DIRECTED__ == false) g[b].pb({a, c});
    return is;
}

template <class T> bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T> bool chmin(T &a, const T &b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}

// Debug
#ifdef NDEBUG
#define debug(...)
#define dumpi(a, h, w)
#define vdumpi(a, n)
#define dump(a, h, w)
#define vdump(a, n)
#else
#define debug(...)                                                                                 \
    {                                                                                              \
        cerr << __LINE__ << ": " << #__VA_ARGS__ << " = ";                                         \
        for (auto &&__i : {__VA_ARGS__}) cerr << "[" << __i << "] ";                               \
        cerr << rt;                                                                                \
    }

#define dumpi(a, h, w)                                                                             \
    {                                                                                              \
        cerr << __LINE__ << ": " << #a << " = [" << rt;                                            \
        rep(__i, h) {                                                                              \
            if (__i) cerr << ",\n";                                                                \
            cerr << "[";                                                                           \
            rep(__j, w) {                                                                          \
                if (__j) cerr << ", ";                                                             \
                if (abs(a[__i][__j]) >= INF / 2 and a[__i][__j] <= -INF / 2) cerr << '-';          \
                if (abs(a[__i][__j]) >= INF / 2) cerr << "∞";                                      \
                else                                                                               \
                    cerr << a[__i][__j];                                                           \
            }                                                                                      \
            cerr << "]";                                                                           \
        }                                                                                          \
        cerr << "\n]" << rt;                                                                       \
    }

#define vdumpi(a, n)                                                                               \
    {                                                                                              \
        cerr << __LINE__ << ": " << #a << " = [";                                                  \
        rep(__i, n) {                                                                              \
            if (__i) cerr << ", ";                                                                 \
            if (abs(a[__i]) >= INF / 2 and a[__i] <= -INF / 2) cerr << '-';                        \
            if (abs(a[__i]) >= INF / 2) cerr << "∞";                                               \
            else                                                                                   \
                cerr << a[__i];                                                                    \
        }                                                                                          \
        cerr << "]" << rt;                                                                         \
    }

#define dump(a, h, w)                                                                              \
    {                                                                                              \
        cerr << __LINE__ << ": " << #a << " = [" << rt;                                            \
        rep(__i, h) {                                                                              \
            if (__i) cerr << ",\n";                                                                \
            cerr << "[";                                                                           \
            rep(__j, w) {                                                                          \
                if (__j) cerr << ", ";                                                             \
                cerr << a[__i][__j];                                                               \
            }                                                                                      \
            cerr << "]";                                                                           \
        }                                                                                          \
        cerr << "\n]" << rt;                                                                       \
    }

#define vdump(a, n)                                                                                \
    {                                                                                              \
        cerr << __LINE__ << ": " << #a << " = [";                                                  \
        rep(__i, n) {                                                                              \
            if (__i) cerr << ", ";                                                                 \
            cerr << a[__i];                                                                        \
        }                                                                                          \
        cerr << "]" << rt;                                                                         \
    }
#endif

template <class S, class T> istream &operator>>(istream &is, pair<S, T> &p) {
    is >> p.first >> p.second;
    return is;
}
template <class S, class T> ostream &operator<<(ostream &os, const pair<S, T> &p) {
    os << p.first << ' ' << p.second;
    return os;
}

// Loop
#define inc(i, a, n) for (ll i = (a), _##i = (n); i <= _##i; ++i)
#define dec(i, a, n) for (ll i = (a), _##i = (n); i >= _##i; --i)
#define rep(i, n) for (ll i = 0, _##i = (n); i < _##i; ++i)
#define each(i, a) for (auto &&i : a)

// Stream
#define fout(n) cout << fixed << setprecision(n)
struct io {
    io() { cin.tie(nullptr), ios::sync_with_stdio(false); }
} io;

// Speed
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#pragma GCC optimize("Ofast,unroll-loops")

// Math
inline constexpr ll gcd(const ll a, const ll b) { return b ? gcd(b, a % b) : a; }
inline constexpr ll lcm(const ll a, const ll b) { return a / gcd(a, b) * b; }

inline constexpr ll modulo(const ll n, const ll m = MOD) {
    ll k = n % m;
    return k + m * (k < 0);
}
inline constexpr ll chmod(ll &n, const ll m = MOD) {
    n %= m;
    return n += m * (n < 0);
}
inline constexpr ll mpow(ll a, ll n, const ll m = MOD) {
    ll r = 1;
    rep(i, 64) {
        if (n & (1LL << i)) r *= a;
        chmod(r, m);
        a *= a;
        chmod(a, m);
    }
    return r;
}
inline ll inv(const ll n, const ll m = MOD) {
    ll a = n, b = m, x = 1, y = 0;
    while (b) {
        ll t = a / b;
        a -= t * b;
        swap(a, b);
        x -= t * y;
        swap(x, y);
    }
    return modulo(x, m);
}
unsigned long long binary_gcd(unsigned long long x, unsigned long long y) {
    if (!x | !y) return x | y;
    unsigned long long cx = __builtin_ctzll(x), cy = __builtin_ctzll(y);
    x >>= cx, y >>= cy;
    while (x ^ y) {
        if (x > y) {
            x = (x - y) >> __builtin_ctzll(x ^ y);
        } else {
            y = (y - x) >> __builtin_ctzll(x ^ y);
        }
    }
    return x << min(cx, cy);
}

inline long long binary_gcd(long long x, long long y) {
    return binary_gcd((unsigned long long) (abs(x)), (unsigned long long) (abs(y)));
}

#define codeforces                                                                                 \
    ll testcases;                                                                                  \
    cin >> testcases;                                                                              \
    rep(testcase, testcases)
#define gcj(s) cout << s << testcase + 1 << ": "

#pragma endregion

/**
 * @brief Primal Dual(最小費用流)
 * @docs docs/primal-dual.md
 */
template <typename flow_t, typename cost_t> struct PrimalDual {
    struct edge {
        int to;
        flow_t cap;
        cost_t cost;
        int rev;
        bool isrev;
    };

    vector<vector<edge>> graph;
    vector<cost_t> potential, min_cost;
    vector<int> prevv, preve;
    const cost_t INF;

    PrimalDual(int V) : graph(V), INF(numeric_limits<cost_t>::max()) {}

    void add_edge(int from, int to, flow_t cap, cost_t cost) {
        graph[from].emplace_back((edge){to, cap, cost, (int) graph[to].size(), false});
        graph[to].emplace_back((edge){from, 0, -cost, (int) graph[from].size() - 1, true});
    }

    cost_t min_cost_flow(int s, int t, flow_t f) {
        int V = (int) graph.size();
        cost_t ret = 0;
        using Pi = pair<cost_t, int>;
        priority_queue<Pi, vector<Pi>, greater<Pi>> que;
        potential.assign(V, 0);
        preve.assign(V, -1);
        prevv.assign(V, -1);

        while (f > 0) {
            min_cost.assign(V, INF);
            que.emplace(0, s);
            min_cost[s] = 0;
            while (!que.empty()) {
                Pi p = que.top();
                que.pop();
                if (min_cost[p.second] < p.first) continue;
                for (int i = 0; i < (int) graph[p.second].size(); i++) {
                    edge &e = graph[p.second][i];
                    cost_t nextCost =
                        min_cost[p.second] + e.cost + potential[p.second] - potential[e.to];
                    if (e.cap > 0 && min_cost[e.to] > nextCost) {
                        min_cost[e.to] = nextCost;
                        prevv[e.to] = p.second, preve[e.to] = i;
                        que.emplace(min_cost[e.to], e.to);
                    }
                }
            }
            if (min_cost[t] == INF) return -1;
            for (int v = 0; v < V; v++) potential[v] += min_cost[v];
            flow_t addflow = f;
            for (int v = t; v != s; v = prevv[v]) {
                addflow = min(addflow, graph[prevv[v]][preve[v]].cap);
            }
            f -= addflow;
            ret += addflow * potential[t];
            for (int v = t; v != s; v = prevv[v]) {
                edge &e = graph[prevv[v]][preve[v]];
                e.cap -= addflow;
                graph[v][e.rev].cap += addflow;
            }
        }
        return ret;
    }

    void output() {
        for (int i = 0; i < graph.size(); i++) {
            for (auto &e : graph[i]) {
                if (e.isrev) continue;
                auto &rev_e = graph[e.to][e.rev];
                cout << i << "->" << e.to << " (flow: " << rev_e.cap << "/" << rev_e.cap + e.cap
                     << ")" << endl;
            }
        }
    }
};

signed main() {
    ll n;
    while (cin >> n, n) {
        vector<ll> x(n), y(n), z(n), a;
        rep(i, n) cin >> x[i] >> y[i] >> z[i], x[i]--, a.pb(x[i]), a.pb(y[i]), a.pb(z[i]);
        sort(all(a));
        a.erase(unique(all(a)), a.end());
        ll m = a.size();
        PrimalDual<ll, ll> pd(m);
        rep(i, m - 1) pd.add_edge(i, i + 1, 100000, 0);
        rep(i, n) {
            ll xi = lower_bound(all(a), x[i]) - a.begin();
            ll yi = lower_bound(all(a), y[i]) - a.begin();
            assert(xi < yi);
            pd.add_edge(xi, yi, 1, -z[i]);
        }
        ll ans = pd.min_cost_flow(0, m - 1, 2);
        cout << -ans << rt;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3752
final_rank: 3

code_snippet: #include<bits/stdc++.h>
#define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i)
#define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i)
#define foreach(i, n) for(auto &i:(n))
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
#define lambda(RES_TYPE, ...) (function<RES_TYPE(__VA_ARGS__)>)[&](__VA_ARGS__) -> RES_TYPE
#define method(FUNC_NAME, RES_TYPE, ...) function<RES_TYPE(__VA_ARGS__)> FUNC_NAME = lambda(RES_TYPE, __VA_ARGS__)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
//const ll MOD = (ll)1e9+7;
const ll MOD = 998244353;
const int INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
template<class t>
using vvector = vector<vector<t>>;
template<class t>
using vvvector = vector<vector<vector<t>>>;
template<class t>
using priority_queuer = priority_queue<t, vector<t>, greater<t>>;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}
#ifdef DEBUG
#define debug(x) cout<<"LINE "<<__LINE__<<": "<<#x<<" = "<<x<<endl;
#else
#define debug(x) (void)0
#endif

namespace templates{
    ll modpow(ll x, ll b,ll mod=MOD){
        ll res = 1;
        while(b){
            if(b&1)res = res * x % mod;
            x = x * x % mod;
            b>>=1;
        }
        return res;
    }

    ll modinv(ll x){
        return modpow(x, MOD-2);
    }

    bool was_output = false;

    void print();
    template <class t> void print(const vector<t> &);
    template <class t, class u> void print(const pair<t, u> &);
    template <class t> void print(const t&);
    template <class Head, class... Tail> void print(const Head&, const Tail&...);

    template <class t> void println(const vector<vector<t>>&);
    template <class t> void println(const vector<t>&);
    template <class t> void println(const t&);
    template <class Head, class... Tail> void println(const Head&, const Tail&...);
    void println();
    void newline();

    void print(){
        return;
    }

    template <class t>
    void print(const vector<t>&x){
        for(const t&i:x)print(i);
    }
    template <class t, class u>
    void print(const pair<t,u>&p){
        print(p.first);
        print(p.second);
    }
    template <class t>
    void print(const t&x){
        if(was_output)cout<<" ";
        cout<<x;
        was_output = true;
    }
    template <class Head, class... Tail>
    void print(const Head&head,const Tail&...tail){
        print(head);
        print(tail...);
    }

    template<class t>
    void println(const vector<vector<t>>&x){
        for(vector<t> i:x)println(i);
    }
    template<class t>
    void println(const vector<t>&x){
        for(const t&i:x)print(i);
        println();
    }
    template <class t>
    void println(const t&x){
        print(x);
        println();
    }
    void println(){
        if(was_output){
            cout << endl;
            was_output = false;
        }
    }
    template <class Head, class... Tail>
    void println(const Head&head,const Tail&...tail){
        print(head);
        println(tail...);
    }

    void newline(){
        was_output = true;
        println();
    }

    template<class t>
    istream& operator>>(istream&is, vector<t>&x){
        for(auto &i:x)is >> i;
        return is;
    }

    template<class t, class u>
    istream& operator>>(istream&is, pair<t, u>&x){
        is >> x.first >> x.second;
        return is;
    }

    template<class t>
    ostream& operator<<(ostream&os, vector<t> &v){
        os << "{";
        for(t &i:v){
            os << i << ", ";
        }
        os << "}";
        return os;
    }

    template<class t = long long>
    t in(){
        t res; cin >> res; return res;
    }

    template<class t>
    vector<t> sorted(vector<t> line,function<bool(t,t)> comp=[](t a,t b){return a<b;}){
        sort(line.begin(),line.end(),comp);
        return line;
    }

    template<class t>
    vector<t> reversed(vector<t> line){
        reverse(line.begin(),line.end());
        return line;
    }
    string reversed(string str){
        reverse(str.begin(),str.end());
        return str;
    }

    long long gcd(long long a,long long b){
        while(b){
            a %= b;
            swap(a,b);
        }
        return a;
    }

    long long lcm(long long a,long long b){
        return a / gcd(a,b) * b;
    }

    class output_initializer{
    public:
        output_initializer(){
            ios::sync_with_stdio(false);
            cin.tie(nullptr);
            cout << setprecision(20);
        }
    };output_initializer OUTPUT_INITIALIZER_INSTANCE = output_initializer();
}

using namespace templates;

class bit2d{
public:
    int h;
    int w;
    vvector<int> table;
    bit2d(int h,int w,int init=0):h(h),w(w),table(h,vector<int>(w,init)){}

    void add(int y,int x,int v){
        for(int i=y+1;i<h;i+=(i&-i)){
            for(int j=x+1;j<w;j+=(j&-j)){
                table[i][j] = max(table[i][j],v);
            }
        }
    }
    int sum(int y,int x){
        int res = 0;
        for(int i=y;i>0;i-=(i&-i)){
            for(int j=x;j>0;j-=(j&-j)){
                res = max(res,table[i][j]);
            }
        }
        return res;
    }
};

ll func(int n){
    bit2d bi(400,400);
    struct record{
        int from;
        int to;
        int cost;
        record(){}
        record(int from,int to,int cost):from(from),to(to),cost(cost){}
    };
    vector<record> records(n);
    foreach(i,records){
        i.from = in();
        i.to = in();
        i.cost = in();
    }
    sort(all(records),lambda(bool,record a,record b){return a.from < b.from;});
    foreach(rec,records){
        per(i,366){
            bi.add(rec.to,i,bi.sum(rec.from,i+1)+rec.cost);
            bi.add(i,rec.to,bi.sum(i+1,rec.from)+rec.cost);
        }
    }
    return bi.sum(366,366);
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while(true){
        int n = in();
        if(n==0)break;
        println(func(n));
    }
    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 3840
final_rank: 4

code_snippet: #include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
using namespace std;

int main() {
int n;
while (scanf("%d", &n) == 1) {
  if (n == 0) break;
  int m = 365;
  vector<int> l(n), r(n), c(n);
  for (int i = 0; i < n; i++) {
    scanf("%d%d%d", &l[i], &r[i], &c[i]);
  }
  vector<int> seq(n);
  for (int i = 0; i < n; i++) seq[i] = i;
  sort(seq.begin(), seq.end(), [&](auto u, auto v) {
    return r[u] < r[v];
  });
  vector<vector<int>> f(m + 1, vector<int> (m + 1, 0));
  // f[0][0] = 0;
  int ans = 0;
  for (int g = 0; g < n; g++) {
    int it = seq[g];
    vector<vector<int>> nf(m + 1, vector<int> (m + 1, 0));
    // printf("it = %d\n", it);
    for (int i = 0; i <= m; i++) {
      for (int j = 0; j <= m; j++) {
        if (i) f[i][j] = max(f[i][j], f[i - 1][j]);
        if (j) f[i][j] = max(f[i][j], f[i][j - 1]);
        nf[i][j] = f[i][j];
        if (i == r[it]) nf[i][j] = max(nf[i][j], f[l[it] - 1][j] + c[it]);
        if (j == r[it]) nf[i][j] = max(nf[i][j], f[i][l[it] - 1] + c[it]);
        // printf("f[%d][%d] = %d\n", i, j, nf[i][j]);
        ans = max(ans, nf[i][j]);
      }
    }
    swap(f, nf);
  }
  printf("%d\n", ans);
}
  return 0;  
}
/*
4
5 15 5000
22 23 5500
10 11 9000
7 7 6000
*/
accuracy: 1
time_ms: 1000
memory_kb: 3572
final_rank: 13

code_snippet: #include<bits/stdc++.h>
#define rep(i,a,...) for(int i = (a)*(strlen(#__VA_ARGS__)!=0);i<(int)(strlen(#__VA_ARGS__)?__VA_ARGS__:(a));++i)
#define per(i,a,...) for(int i = (strlen(#__VA_ARGS__)?__VA_ARGS__:(a))-1;i>=(int)(strlen(#__VA_ARGS__)?(a):0);--i)
#define foreach(i, n) for(auto &i:(n))
#define all(x) (x).begin(), (x).end()
#define bit(x) (1ll << (x))
#define lambda(RES_TYPE, ...) (function<RES_TYPE(__VA_ARGS__)>)[&](__VA_ARGS__) -> RES_TYPE
#define method(FUNC_NAME, RES_TYPE, ...) function<RES_TYPE(__VA_ARGS__)> FUNC_NAME = lambda(RES_TYPE, __VA_ARGS__)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
//const ll MOD = (ll)1e9+7;
const ll MOD = 998244353;
const int INF = (ll)1e9+7;
const ll INFLL = (ll)1e18;
template<class t>
using vvector = vector<vector<t>>;
template<class t>
using vvvector = vector<vector<vector<t>>>;
template<class t>
using priority_queuer = priority_queue<t, vector<t>, greater<t>>;
template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;}
template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;}
#ifdef DEBUG
#define debug(x) cout<<"LINE "<<__LINE__<<": "<<#x<<" = "<<x<<endl;
#else
#define debug(x) (void)0
#endif

namespace templates{
    ll modpow(ll x, ll b,ll mod=MOD){
        ll res = 1;
        while(b){
            if(b&1)res = res * x % mod;
            x = x * x % mod;
            b>>=1;
        }
        return res;
    }

    ll modinv(ll x){
        return modpow(x, MOD-2);
    }

    bool was_output = false;

    void print();
    template <class t> void print(const vector<t> &);
    template <class t, class u> void print(const pair<t, u> &);
    template <class t> void print(const t&);
    template <class Head, class... Tail> void print(const Head&, const Tail&...);

    template <class t> void println(const vector<vector<t>>&);
    template <class t> void println(const vector<t>&);
    template <class t> void println(const t&);
    template <class Head, class... Tail> void println(const Head&, const Tail&...);
    void println();
    void newline();

    void print(){
        return;
    }

    template <class t>
    void print(const vector<t>&x){
        for(const t&i:x)print(i);
    }
    template <class t, class u>
    void print(const pair<t,u>&p){
        print(p.first);
        print(p.second);
    }
    template <class t>
    void print(const t&x){
        if(was_output)cout<<" ";
        cout<<x;
        was_output = true;
    }
    template <class Head, class... Tail>
    void print(const Head&head,const Tail&...tail){
        print(head);
        print(tail...);
    }

    template<class t>
    void println(const vector<vector<t>>&x){
        for(vector<t> i:x)println(i);
    }
    template<class t>
    void println(const vector<t>&x){
        for(const t&i:x)print(i);
        println();
    }
    template <class t>
    void println(const t&x){
        print(x);
        println();
    }
    void println(){
        if(was_output){
            cout << endl;
            was_output = false;
        }
    }
    template <class Head, class... Tail>
    void println(const Head&head,const Tail&...tail){
        print(head);
        println(tail...);
    }

    void newline(){
        was_output = true;
        println();
    }

    template<class t>
    istream& operator>>(istream&is, vector<t>&x){
        for(auto &i:x)is >> i;
        return is;
    }

    template<class t, class u>
    istream& operator>>(istream&is, pair<t, u>&x){
        is >> x.first >> x.second;
        return is;
    }

    template<class t>
    ostream& operator<<(ostream&os, vector<t> &v){
        os << "{";
        for(t &i:v){
            os << i << ", ";
        }
        os << "}";
        return os;
    }

    template<class t = long long>
    t in(){
        t res; cin >> res; return res;
    }

    template<class t>
    vector<t> sorted(vector<t> line,function<bool(t,t)> comp=[](t a,t b){return a<b;}){
        sort(line.begin(),line.end(),comp);
        return line;
    }

    template<class t>
    vector<t> reversed(vector<t> line){
        reverse(line.begin(),line.end());
        return line;
    }
    string reversed(string str){
        reverse(str.begin(),str.end());
        return str;
    }

    long long gcd(long long a,long long b){
        while(b){
            a %= b;
            swap(a,b);
        }
        return a;
    }

    long long lcm(long long a,long long b){
        return a / gcd(a,b) * b;
    }

    class output_initializer{
    public:
        output_initializer(){
            ios::sync_with_stdio(false);
            cin.tie(nullptr);
            cout << setprecision(20);
        }
    };output_initializer OUTPUT_INITIALIZER_INSTANCE = output_initializer();
}

using namespace templates;

class binary_indexed_tree{
public:
    int n;
    vector<int> value;
    binary_indexed_tree(int n):n(n),value(n+1,0){};
    void add(int p,int v){
        for(int i=p+1;i<n;i+=i&(-i)){
            value[i] = max(value[i],v);
        }
    }
    int sum(int p){
        int res = 0;
        for(int i=p;i;i-=i&(-i)){
            res = max(res,value[i]);
        }
        return res;
    }
};

int func(int n){
    using T = tuple<int,int,int>;
    vector<T> line(n);
    foreach(i,line){
        int l = in();
        int r = in();
        int c = in();
        line.emplace_back(l-1,r-1,c);
    }
    sort(all(line),lambda(bool,T a,T b){
            return get<0>(a) < get<0>(b);
        });
    vector<binary_indexed_tree> dp1(400,binary_indexed_tree(400));
    vector<binary_indexed_tree> dp2(400,binary_indexed_tree(400));
    int res = 0;
    foreach(a,line){
        int l = get<0>(a);
        int r = get<1>(a);
        int c = get<2>(a);
        per(i,365){
            {
                int next = dp1[i].sum(l) + c;
                chmax(res,next);
                dp1[i].add(r,next);
                dp2[r].add(i,next);
            }
            {
                int next = dp2[i].sum(l) + c;
                chmax(res,next);
                dp2[i].add(r,next);
                dp1[r].add(i,next);
            }
        }
    }
    return res;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    while(true){
        int n = in();
        if(n==0)break;
        println(func(n));
    }
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 4332
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
int n;

void solve(){
    vector<vector<int>> lrc(n, vector<int>(3));
    int d = 0;
    for(int i = 0; i < n; i++){
        cin >> lrc[i][1] >> lrc[i][0] >> lrc[i][2];
        d = max(d, max(lrc[i][1], lrc[i][0]));
    }
    sort(lrc.begin(), lrc.end());
    d++;
    vector<vector<int>> dp(d, vector<int>(d, 0));
    int l, r, c;
    for(auto tmp: lrc){
        l = tmp[1];
        r = tmp[0];
        c = tmp[2];
        vector<int> col(d, 0);
        for(int i = 0; i < l; i++) for(int j = 0; j < d; j++){
            col[j] = max(col[j], dp[i][j] + c);
        }
        
        vector<int> row(d, 0);
        for(int j = 0; j < l; j++) for(int i = 0; i < d; i++){
            col[i] = max(col[i], dp[i][j] + c);
        }
        
        for(int j = 0; j < d; j++){
            dp[r][j] = max(dp[r][j], col[j]);
            dp[j][r] = max(dp[j][r], row[j]);
        }
    }
    
    int ans = 0;
    for(int i = 0; i < d; i++) for(int j = 0; j < d; j++) ans = max(ans, dp[i][j]);
    cout << ans << "\n";
    
}

int main(void){
    while(1){
        cin >> n;
        if(n == 0) break;
        solve();
    }
}
accuracy: 1
time_ms: 150
memory_kb: 3928
final_rank: 5

code_snippet: // #pragma comment(linker, "/stack:200000000")

#include <bits/stdc++.h>

#include <limits>
#include <type_traits>

namespace suisen {
// ! utility
template <typename ...Types>
using constraints_t = std::enable_if_t<std::conjunction_v<Types...>, std::nullptr_t>;
template <bool cond_v, typename Then, typename OrElse>
constexpr decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// ! function
template <typename ReturnType, typename Callable, typename ...Args>
using is_same_as_invoke_result = std::is_same<std::invoke_result_t<Callable, Args...>, ReturnType>;
template <typename F, typename T>
using is_uni_op = is_same_as_invoke_result<T, F, T>;
template <typename F, typename T>
using is_bin_op = is_same_as_invoke_result<T, F, T, T>;

template <typename Comparator, typename T>
using is_comparator = std::is_same<std::invoke_result_t<Comparator, T, T>, bool>;

// ! integral
template <typename T, typename = constraints_t<std::is_integral<T>>>
constexpr int bit_num = std::numeric_limits<std::make_unsigned_t<T>>::digits;
template <typename T, unsigned int n>
struct is_nbit { static constexpr bool value = bit_num<T> == n; };
template <typename T, unsigned int n>
static constexpr bool is_nbit_v = is_nbit<T, n>::value;

// ?
template <typename T>
struct safely_multipliable {};
template <>
struct safely_multipliable<int> { using type = long long; };
template <>
struct safely_multipliable<long long> { using type = __int128_t; };
template <>
struct safely_multipliable<float> { using type = float; };
template <>
struct safely_multipliable<double> { using type = double; };
template <>
struct safely_multipliable<long double> { using type = long double; };
template <typename T>
using safely_multipliable_t = typename safely_multipliable<T>::type;

} // namespace suisen

// ! type aliases
using i128 = __int128_t;
using u128 = __uint128_t;
using ll = long long;
using uint = unsigned int;
using ull  = unsigned long long;

template <typename T> using vec  = std::vector<T>;
template <typename T> using vec2 = vec<vec <T>>;
template <typename T> using vec3 = vec<vec2<T>>;
template <typename T> using vec4 = vec<vec3<T>>;

template <typename T>
using pq_greater = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <typename T, typename U>
using umap = std::unordered_map<T, U>;

// ! macros (capital: internal macro)
#define OVERLOAD2(_1,_2,name,...) name
#define OVERLOAD3(_1,_2,_3,name,...) name
#define OVERLOAD4(_1,_2,_3,_4,name,...) name

#define REP4(i,l,r,s)  for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l);i<(r);i+=(s))
#define REP3(i,l,r)    REP4(i,l,r,1)
#define REP2(i,n)      REP3(i,0,n)
#define REPINF3(i,l,s) for(std::remove_reference_t<std::remove_const_t<decltype(l)>>i=(l);;i+=(s))
#define REPINF2(i,l)   REPINF3(i,l,1)
#define REPINF1(i)     REPINF2(i,0)
#define RREP4(i,l,r,s) for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l)+fld((r)-(l)-1,s)*(s);i>=(l);i-=(s))
#define RREP3(i,l,r)   RREP4(i,l,r,1)
#define RREP2(i,n)     RREP3(i,0,n)

#define rep(...)    OVERLOAD4(__VA_ARGS__, REP4   , REP3   , REP2   )(__VA_ARGS__)
#define rrep(...)   OVERLOAD4(__VA_ARGS__, RREP4  , RREP3  , RREP2  )(__VA_ARGS__)
#define repinf(...) OVERLOAD3(__VA_ARGS__, REPINF3, REPINF2, REPINF1)(__VA_ARGS__)

#define CAT_I(a, b) a##b
#define CAT(a, b) CAT_I(a, b)
#define UNIQVAR(tag) CAT(tag, __LINE__)
#define loop(n) for (std::remove_reference_t<std::remove_const_t<decltype(n)>> UNIQVAR(loop_variable) = n; UNIQVAR(loop_variable) --> 0;)

#define all(iterable) (iterable).begin(), (iterable).end()
#define input(type, ...) type __VA_ARGS__; read(__VA_ARGS__)

// ! I/O utilities

// pair
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U> &a) {
    return out << a.first << ' ' << a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return out;
    } else {
        out << std::get<N>(a);
        if constexpr (N + 1 < std::tuple_size_v<std::tuple<Args...>>) {
            out << ' ';
        }
        return operator<<<N + 1>(out, a);
    }
}
// vector
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
inline void print() { std::cout << '\n'; }
template <typename Head, typename... Tail>
inline void print(const Head &head, const Tail &...tails) {
    std::cout << head;
    if (sizeof...(tails)) std::cout << ' ';
    print(tails...);
}
template <typename Iterable>
auto print_all(const Iterable& v, std::string sep = " ", std::string end = "\n") -> decltype(std::cout << *v.begin(), void()) {
    for (auto it = v.begin(); it != v.end();) {
        std::cout << *it;
        if (++it != v.end()) std::cout << sep;
    }
    std::cout << end;
}

// pair
template <typename T, typename U>
std::istream& operator>>(std::istream& in, std::pair<T, U> &a) {
    return in >> a.first >> a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return in;
    } else {
        return operator>><N + 1>(in >> std::get<N>(a), a);
    }
}
// vector
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
template <typename ...Args>
void read(Args &...args) {
    ( std::cin >> ... >> args );
}

// ! integral utilities

// Returns pow(-1, n)
template <typename T>
constexpr inline int pow_m1(T n) {
    return -(n & 1) | 1;
}
// Returns pow(-1, n)
template <>
constexpr inline int pow_m1<bool>(bool n) {
    return -int(n) | 1;
}

// Returns floor(x / y)
template <typename T>
constexpr inline T fld(const T x, const T y) {
    return (x ^ y) >= 0 ? x / y : (x - (y + pow_m1(y >= 0))) / y;
}
template <typename T>
constexpr inline T cld(const T x, const T y) {
    return (x ^ y) <= 0 ? x / y : (x + (y + pow_m1(y >= 0))) / y;
}

template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcount(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcountll(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clzll(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctzll(x) : suisen::bit_num<T>; }
template <typename T>
constexpr inline int floor_log2(const T x) { return suisen::bit_num<T> - 1 - count_lz(x); }
template <typename T>
constexpr inline int ceil_log2(const T x)  { return floor_log2(x) + ((x & -x) != x); }
template <typename T>
constexpr inline int kth_bit(const T x, const unsigned int k) { return (x >> k) & 1; }
template <typename T>
constexpr inline int parity(const T x) { return popcount(x) & 1; }

struct all_subset {
    struct all_subset_iter {
        const int s; int t;
        constexpr all_subset_iter(int s) : s(s), t(s + 1) {}
        constexpr auto operator*() const { return t; }
        constexpr auto operator++() {}
        constexpr auto operator!=(std::nullptr_t) { return t ? (--t &= s, true) : false; }
    };
    int s;
    constexpr all_subset(int s) : s(s) {}
    constexpr auto begin() { return all_subset_iter(s); }
    constexpr auto end()   { return nullptr; }
};

// ! container

template <typename T, typename Comparator, suisen::constraints_t<suisen::is_comparator<Comparator, T>> = nullptr>
auto priqueue_comp(const Comparator comparator) {
    return std::priority_queue<T, std::vector<T>, Comparator>(comparator);
}

template <typename Iterable>
auto isize(const Iterable &iterable) -> decltype(int(iterable.size())) {
    return iterable.size();
}

template <typename T, typename Gen, suisen::constraints_t<suisen::is_same_as_invoke_result<T, Gen, int>> = nullptr>
auto generate_vector(int n, Gen generator) {
    std::vector<T> v(n);
    for (int i = 0; i < n; ++i) v[i] = generator(i);
    return v;
}

template <typename T>
void sort_unique_erase(std::vector<T> &a) {
    std::sort(a.begin(), a.end());
    a.erase(std::unique(a.begin(), a.end()), a.end());
}

// ! other utilities

// x <- min(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmin(T &x, const T &y) {
    if (y >= x) return false;
    x = y;
    return true;
}
// x <- max(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmax(T &x, const T &y) {
    if (y <= x) return false;
    x = y;
    return true;
}

namespace suisen {}
using namespace suisen;
using namespace std;

struct io_setup {
    io_setup(int precision = 20) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(precision);
    }
} io_setup_ {};

// ! code from here

constexpr int D = 366;

void solve(const int n, vector<tuple<int, int, int>> &applicants) {
    vector dp(D, vector(D, 0LL));
    sort(all(applicants), [](auto &p1, auto &p2) {
        auto &[l1, r1, w1] = p1;
        auto &[l2, r2, w2] = p2;
        return r1 == r2 ? l1 < l2 : r1 < r2;
    });
    for (auto &[l, r, w] : applicants) {
        rep(i, l + 1) rep(j, D) {
            chmax(dp[r][j], dp[i][j] + w);
        }
        rep(i, D) rep(j, i) {
            chmax(dp[i][j], dp[j][i]);
            chmax(dp[j][i], dp[i][j]);
        }
    }
    long long ans = 0;
    for (auto &v : dp) chmax(ans, *max_element(all(v)));
    print(ans);
}

int main() {
    while (true) {
        input(int, n);
        if (n == 0) break;
        vector<tuple<int, int, int>> applicants(n);
        read(applicants);
        for (auto &[l, r, w] : applicants) --l;
        solve(n, applicants);
    }
}
accuracy: 1
time_ms: 300
memory_kb: 4076
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    while (true) {
        int N;
        cin >> N;
        if (N == 0) break;
        vector<vector<pair<int, int>>> apps(366);
        for (int t = 0; t < N; ++t) {
            int i, j, w;
            cin >> i >> j >> w;
            apps[j].push_back({i - 1, w});
        }
        vector<vector<int>> dp(366, vector<int>(366));
        for (int j = 1; j <= 365; ++j) {
            for (int p = 0; p < j; ++p) {
                dp[j][p] = dp[j-1][p];
                dp[p][j] = dp[p][j-1];
            }
            dp[j][j] = dp[j-1][j-1];
            for (auto [i, w] : apps[j]) {
                auto ndp = dp;
                for (int p = 0; p <= j; ++p) {
                    ndp[j][p] = max(ndp[j][p], dp[i][p] + w);
                    ndp[p][j] = max(ndp[p][j], dp[p][i] + w);
                }
                dp.swap(ndp);
            }
        }
        cout << dp[365][365] << "\n";
    }
}
accuracy: 1
time_ms: 220
memory_kb: 3972
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;

int dp[2][366][366];

int main() {
    while (true) {
        int n;
        cin >> n;
        if(n == 0) {
            return 0;
        }
        vector<array<int,3>>ar(n);
        for(int i = 0; i < n; i++) {
            cin >> ar[i][0] >> ar[i][1] >> ar[i][2];
            ar[i][0]--;
        }
        sort(ar.begin(),ar.end());
        for(int k = 0; k < n; k++) {
            for(int i = 0; i <= 365; i++) {
                for(int j = 0; j <= 365; j++) {
                    dp[1][i][j] = max(dp[1][i][j],dp[0][i][j]);
                    if(i <= ar[k][0]) {
                        dp[1][ar[k][1]][j] = max(dp[1][ar[k][1]][j],dp[0][i][j]+ar[k][2]);
                    }
                    if(j <= ar[k][0]) {
                        dp[1][i][ar[k][1]] = max(dp[1][i][ar[k][1]],dp[0][i][j]+ar[k][2]);
                    }
                }
            }
            for(int i = 0; i <= 365; i++) {
                for(int j = 0; j <= 365; j++) {
                    dp[0][i][j] = dp[1][i][j];
                    dp[1][i][j] = 0;
                }
            }
        }
        int ans = 0;
        for(int k = 0; k <= 1; k++) {
            for(int i = 0; i <= 365; i++) {
                for(int j = 0; j <= 365; j++) {
                    ans = max(ans,dp[k][i][j]);
                    dp[k][i][j] = 0;
                }
            }
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 620
memory_kb: 4252
final_rank: 12

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>

#define rep(i, a, n) for (int i = (int)(a); i < (int)(n); i++)
#define rrep(i, a, n) for (int i = ((int)(n-1)); i >= (int)(a); i--)

using i64 = std::int64_t;

constexpr i64 mod = 1e9 + 7;

constexpr i64 LNF = 1e18;

constexpr int sz = 365;

struct Query {
    int i,j;
    i64 w;
};

template <class T>
inline bool chmin(T &a, T b) {
    if (a > b){
        a = b;
        return true;
    }
    return false;
}
 
template <class T>
inline bool chmax(T &a, T b) {
    if (a < b){
        a = b;
        return true;
    }
    return false;
}

int main() {
    int n;
    while(std::cin >> n, n != 0) {
        std::vector dp(sz+1, std::vector<i64>(sz+1, -1));
        dp[0][0] = 0;
        std::vector<Query> p(n);
        rep(i,0,n) {
            std::cin >> p[i].i >> p[i].j >> p[i].w;
            p[i].i--;
        }
        std::sort(p.begin(), p.end(), [](const Query &a, const Query &b) -> bool { return a.j == b.j ? a.w > b.w : a.j < b.j; });
        for(auto q: p) {
            int l = q.i;
            int r = q.j;
            i64 w = q.w;
            rrep(i,0,sz+1) {
                rrep(j,0,sz+1) {
                    if(dp[i][j] == -1) continue;
                    if(i <= l) {
                        chmax(dp[r][j], dp[i][j] + w);
                    }
                    if(j <= l) {
                        chmax(dp[i][r], dp[i][j] + w);
                    }
                }
            }
        }
        i64 ans = 0;
        rep(i,0,sz+1) {
            rep(j,0,sz+1) {
                chmax(ans, dp[i][j]);
            }
        }
        std::cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 330
memory_kb: 4412
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;

using P = pair<int,int>;

int main() {
  
  ios::sync_with_stdio(false);
  cin.tie(0);

  int n;
  cin >> n;
  while (n != 0) {
    vector<int> l(n),r(n),w(n);
    for (int i=0;i<n;i++) {
      cin >> l[i] >> r[i] >> w[i];
      l[i]--;
    }
    vector<P> ps(n);
    for (int i=0;i<n;i++) {
      ps[i] = P(r[i],i);
    }
    sort(ps.begin(),ps.end());
    vector<vector<int>> dp(366,vector<int>(366,0));
    for (int j=0;j<n;j++) {
      int ind = ps[j].second;
      queue<P> q;
      for (int s=365*2;s>=0;s--) {
        for (int i=max(s-365,0);i<=min(s,365);i++) {
          // from dp[i][s-i]
          if (min(i,s-i) <= l[ind]) {
            q.push(P(i,s-i));
          }
        }
      }
      while (!q.empty()) {
        P np = q.front();
        q.pop();
        int ni = np.first;
        int nj = np.second;
        if (ni <= l[ind]) {
          dp[r[ind]][nj] = max(dp[r[ind]][nj],dp[ni][nj]+w[ind]);
        }
        if (nj <= l[ind]) {
          dp[ni][r[ind]] = max(dp[ni][r[ind]],dp[ni][nj]+w[ind]);
        }
      }
    }
    int ans = 0;
    for (int i=0;i<=365;i++) {
      for (int j=0;j<=365;j++) {
        ans = max(ans,dp[i][j]);
        //if (i <= 3 && j <= 3) cout << dp[i][j] << ' ';
      }
      //if (i <= 3)cout << endl;
    }
    cout << ans << endl;
    cin >> n;
  }
}
accuracy: 1
time_ms: 1130
memory_kb: 4712
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;

using P = pair<int,int>;

int main() {
  
  ios::sync_with_stdio(false);
  cin.tie(0);

  int n;
  cin >> n;
  while (n != 0) {
    vector<int> l(n),r(n),w(n);
    for (int i=0;i<n;i++) {
      cin >> l[i] >> r[i] >> w[i];
      l[i]--;
    }
    vector<P> ps(n);
    for (int i=0;i<n;i++) {
      ps[i] = P(r[i],i);
    }
    sort(ps.begin(),ps.end());
    vector<vector<int>> dp(366,vector<int>(366,0));
    for (int j=0;j<n;j++) {
      int ind = ps[j].second;
      queue<P> q;
      for (int s=365*2;s>=0;s--) {
        for (int i=max(s-365,0);i<=min(s,365);i++) {
          // from dp[i][s-i]
          if (min(i,s-i) <= l[ind]) {
            q.push(P(i,s-i));
          }
        }
      }
      while (!q.empty()) {
        P np = q.front();
        q.pop();
        int ni = np.first;
        int nj = np.second;
        if (ni <= l[ind]) {
          dp[r[ind]][nj] = max(dp[r[ind]][nj],dp[ni][nj]+w[ind]);
        }
        if (nj <= l[ind]) {
          dp[ni][r[ind]] = max(dp[ni][r[ind]],dp[ni][nj]+w[ind]);
        }
      }
    }
    int ans = 0;
    for (int i=0;i<=365;i++) {
      for (int j=0;j<=365;j++) {
        ans = max(ans,dp[i][j]);
        //if (i <= 3 && j <= 3) cout << dp[i][j] << ' ';
      }
      //if (i <= 3)cout << endl;
    }
    cout << ans << endl;
    cin >> n;
  }
}
accuracy: 1
time_ms: 1130
memory_kb: 4820
final_rank: 16

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define ALL(x) begin(x),end(x)
#define rep(i,n) for(int i=0;i<(n);i++)
#define debug(v) cout<<#v<<":";for(auto x:v){cout<<x<<' ';}cout<<endl;
#define mod 1000000007
using ll=long long;
const int INF=1000000000;
const ll LINF=1001002003004005006ll;
int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
// ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
template<class T>bool chmax(T &a,const T &b){if(a<b){a=b;return true;}return false;}
template<class T>bool chmin(T &a,const T &b){if(b<a){a=b;return true;}return false;}

struct IOSetup{
    IOSetup(){
        cin.tie(0);
        ios::sync_with_stdio(0);
        cout<<fixed<<setprecision(12);
    }
} iosetup;

template<typename T>
ostream &operator<<(ostream &os,const vector<T>&v){
    for(int i=0;i<(int)v.size();i++) os<<v[i]<<(i+1==(int)v.size()?"":" ");
    return os;
}
template<typename T>
istream &operator>>(istream &is,vector<T>&v){
    for(T &x:v)is>>x;
    return is;
}

template<typename Monoid>
struct SegmentTree{
    using F=function<Monoid(Monoid,Monoid)>;

    private:
    int sz;
    vector<Monoid> seg;

    Monoid query(int a,int b,int k,int l,int r){
        if(a<=l and r<=b)   return seg[k];
        if(b<=l or r<=a)    return M0;
        Monoid L=query(a,b,2*k,l,(l+r)/2);
        Monoid R=query(a,b,2*k+1,(l+r)/2,r);
        return f(L,R);
    }
    template<typename C>
    int find_first(int a,const C &check,Monoid &acc,int k,int l,int r){
        if(k>=sz){
            acc=f(acc,seg[k]);
            if(check(acc))  return -1;
            else            return k-sz;
        }
        int m=(l+r)/2;
        if(m<=a) return find_first(a,check,acc,2*k+1,m,r);
        if(a<=l and check(f(acc,seg[k]))){
            acc=f(acc,seg[k]);
            return -1;
        }
        int x=find_first(a,check,acc,2*k+0,l,m);
        if(x>=0) return x;
        return find_first(a,check,acc,2*k+1,m,r);
    }
    template<typename C>
    int find_last(int b,const C &check,Monoid &acc,int k,int l,int r){
        if(k>=sz){
            acc=f(acc,seg[k]);
            if(check(acc))  return -1;
            else            return k-sz+1;//ここはfalse, +1した位置はtrue
        }
        int m=(l+r)/2;
        if(b<=m) return find_last(b,check,acc,2*k,l,m);
        if(r<=b and check(f(acc,seg[k]))){
            acc=f(acc,seg[k]);
            return -1;
        }
        int x=find_last(b,check,acc,2*k+1,m,r);
        if(x>=0) return x;
        return find_last(b,check,acc,2*k,l,m);
    }

    public:

    F f;
    Monoid M0;// モノイドの元
    SegmentTree(int n,F f,Monoid M0):f(f),M0(M0){
        sz=1;
        while(sz<n)sz<<=1;
        seg.assign(2*sz,M0);
    }
    void set(int k,Monoid x){
        seg[k+sz]=x;
    }
    void build(){
        for(int k=sz-1;k>0;k--) seg[k]=f(seg[2*k],seg[2*k+1]);
    }
    void update(int k,Monoid x){
        k+=sz;
        seg[k]=x;
        k>>=1;
        for(;k;k>>=1) seg[k]=f(seg[2*k],seg[2*k+1]);
    }
    Monoid query(int a,int b){
        return query(a,b,1,0,sz);
    }
    Monoid operator[](const int &k)const{
        return seg[k+sz];
    }

    // http://codeforces.com/contest/914/submission/107505449
    // max x, check(query(a, x)) = true 
    template<typename C>
    int find_first(int a,const C &check){
        Monoid val=M0;
        return find_first(a,check,val,1,0,sz);
    }
    // http://codeforces.com/contest/914/submission/107505582
    // min x, check(query(x, b)) = true
    template<typename C>
    int find_last(int b,C &check){
        Monoid val=M0;
        return find_last(b,check,val,1,0,sz);
    }
};

int segfunc(int x,int y){
    return max(x,y);
}

int N;

const int D=400;

void solve(){
    using T=tuple<int,int,int>;
    vector<T> v;// r, l, w;
    rep(i,N){
        int l,r,w;cin>>l>>r>>w;r++;
        v.emplace_back(r,l,w);
    }
    sort(ALL(v));

    vector<vector<int>> dp(D,vector<int>(D,0));

    vector<SegmentTree<int>>H,W;
    rep(i,D) H.push_back(SegmentTree<int>(D,segfunc,0)),W.push_back(SegmentTree<int>(D,segfunc,0));
    rep(i,D) H[i].build(),W[i].build();

    for(auto [r,l,w]:v){
        {
            for(int i=0;i<D;i++){
                int t=H[i].query(0,l+1)+w;
                if(H[i][r]<t) H[i].update(r,t);
            }
        }
        {
            for(int i=0;i<D;i++){
                int t=W[i].query(0,l+1)+w;
                if(W[i][r]<t) W[i].update(r,t);
            }
        }

        rep(i,D){
            {
                int hval=H[i].query(r,r+1);
                int wval=W[r].query(i,i+1);
                if(hval>wval){
                    if(W[r][i]<hval) W[r].update(i,hval);
                }
                else{
                    if(H[i][r]<wval) H[i].update(r,wval);
                }
            }
            {
                int hval=H[r].query(i,i+1);
                int wval=W[i].query(r,r+1);
                if(hval>wval){
                    if(W[i][r]<hval) W[i].update(r,hval);
                }
                else{
                    if(H[r][i]<wval) H[r].update(i,wval);
                }
            }

        }

        // cout<<l<<" ~ "<<r<<" ) "<<w<<endl;
        // rep(i,8){
        //     rep(j,8){
        //         cout<<max(H[i].query(j,j+1),W[j].query(i,i+1))<<" ";
        //     }
        //     cout<<endl;
        // }
    }


    int mx=0;
    rep(i,D) chmax(mx,H[i].query(0,D));
    rep(i,D) chmax(mx,W[i].query(0,D));
    cout<<mx<<endl;
}

signed main(){
    while(cin>>N,N) solve();
    return 0;
}
accuracy: 1
time_ms: 340
memory_kb: 6984
final_rank: 17

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

const int N=367;

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n;
    while(cin >> n,n){
        vector<vector<int>> dp(N,vector<int>(N));
        vector<pair<pair<int,int>,int>> v(n);
        for(int i=0;i<n;i++){
            cin >> v[i].first.first >> v[i].first.second >> v[i].second;
        }
        sort(v.begin(), v.end(),[&](auto i,auto j){
            return i.first.second<j.first.second;
        });
        for(int i=0;i<n;i++){
            vector<vector<int>> ndp=dp;
            for(int j=0;j<N;j++){
                for(int k=0;k<N;k++){
                    if(j<=v[i].first.first){
                        ndp[v[i].first.second+1][k]=max(ndp[v[i].first.second+1][k],dp[j][k]+v[i].second);
                    }
                    if(k<=v[i].first.first){
                        ndp[j][v[i].first.second+1]=max(ndp[j][v[i].first.second+1],dp[j][k]+v[i].second);
                    }
                }
            }
            swap(dp,ndp);
        }
        int res=0;
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                res=max(res,dp[i][j]);
            }
        }
        cout << res << endl;
    }
}
accuracy: 1
time_ms: 730
memory_kb: 3956
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;

/**
 * @brief compress
 */
template <typename T> map<T, int> compress(vector<T>& v) {
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    map<T, int> res;
    for (int i = 0; i < v.size(); i++) res[v[i]] = i;
    return res;
}

/**
 * @brief Segment Tree
 * @docs docs/datastructure/SegmentTree.md
 */
template <typename Monoid> struct SegmentTree {
    typedef function<Monoid(Monoid, Monoid)> F;
    int n;
    F f;
    Monoid id;
    vector<Monoid> dat;
    SegmentTree(int n_, F f, Monoid id) : f(f), id(id) { init(n_); }
    void init(int n_) {
        n = 1;
        while (n < n_) n <<= 1;
        dat.assign(n << 1, id);
    }
    void build(const vector<Monoid>& v) {
        for (int i = 0; i < (int)v.size(); i++) dat[i + n] = v[i];
        for (int i = n - 1; i; i--) dat[i] = f(dat[i << 1 | 0], dat[i << 1 | 1]);
    }
    void update(int k, Monoid x) {
        dat[k += n] = x;
        while (k >>= 1) dat[k] = f(dat[k << 1 | 0], dat[k << 1 | 1]);
    }
    Monoid query(int a, int b) {
        if (a >= b) return id;
        Monoid vl = id, vr = id;
        for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
            if (l & 1) vl = f(vl, dat[l++]);
            if (r & 1) vr = f(dat[--r], vr);
        }
        return f(vl, vr);
    }
    template <typename C> int find_subtree(int k, const C& check, Monoid& M, bool type) {
        while (k < n) {
            Monoid nxt = type ? f(dat[k << 1 | type], M) : f(M, dat[k << 1 | type]);
            if (check(nxt))
                k = k << 1 | type;
            else
                M = nxt, k = k << 1 | (type ^ 1);
        }
        return k - n;
    }
    // min i s.t. f(seg[a],seg[a+1],...,seg[i]) satisfy "check"
    template <typename C> int find_first(int a, const C& check) {
        Monoid L = id;
        if (a <= 0) {
            if (check(f(L, dat[1]))) return find_subtree(1, check, L, false);
            return -1;
        }
        int b = n;
        for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
            if (l & 1) {
                Monoid nxt = f(L, dat[l]);
                if (check(nxt)) return find_subtree(l, check, L, false);
                L = nxt;
                l++;
            }
        }
        return -1;
    }
    // max i s.t. f(seg[i],...,seg[b-2],seg[b-1]) satisfy "check"
    template <typename C> int find_last(int b, const C& check) {
        Monoid R = id;
        if (b >= n) {
            if (check(f(dat[1], R))) return find_subtree(1, check, R, true);
            return -1;
        }
        int a = n;
        for (int l = a, r = b + n; l < r; l >>= 1, r >>= 1) {
            if (r & 1) {
                Monoid nxt = f(dat[--r], R);
                if (check(nxt)) return find_subtree(r, check, R, true);
                R = nxt;
            }
        }
        return -1;
    }
    Monoid operator[](int i) { return dat[i + n]; }
};

const int INF = 1e9;

struct event {
    int l, r, w;
    event(int l, int r, int w) : l(l), r(r), w(w) {}
    bool operator<(const event& rhs) const { return r < rhs.r; }
};

void solve(int n) {
    vector<int> l(n), r(n), w(n), comp;
    for (int i = 0; i < n; i++) {
        cin >> l[i] >> r[i] >> w[i];
        l[i]--;
        comp.emplace_back(l[i]);
        comp.emplace_back(r[i]);
    }

    map<int, int> mp = compress(comp);
    vector<event> es;
    for (int i = 0; i < n; i++) es.emplace_back(mp[l[i]], mp[r[i]], w[i]);
    sort(es.begin(), es.end());
    int sz = mp.size();
    vector<SegmentTree<int>> seg(sz, SegmentTree<int>(
                                         sz, [](int a, int b) { return max(a, b); }, -INF));
    seg[0].update(0, 0);

    for (int i = 0; i < n; i++) {
        int L = es[i].l, R = es[i].r;
        vector<pair<int, int>> update;
        for (int j = 0; j < sz; j++) {
            seg[j].update(R, max(seg[j][R], seg[j].query(0, L + 1) + es[i].w));
            update.emplace_back(j, R);
        }
        for (auto& p : update) {
            int x = p.first, y = p.second;
            seg[y].update(x, max(seg[y][x], seg[x][y]));
        }
    }

    int ans = -INF;
    for (int i = 0; i < sz; i++) {
        for (int j = 0; j < sz; j++) {
            ans = max(ans, seg[i][j]);
        }
    }

    cout << ans << '\n';
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    while (cin >> n, n) solve(n);
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 4644
final_rank: 9