#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; template auto range(T s, T e) { return views::iota(s, max(s, e)); } template auto range(T n) { return range(0, n); } template void take(vector& vec, int n) { vec.resize(n); for (int i = 0; i < n; ++i) cin >> vec[i]; } template void sout(const Args &...args) { ((cout << args << ' '), ...); } template void soutn(const Args &...args) { ((cout << args << ' '), ...); cout << '\n'; } template struct In2 { T1 a; T2 b; friend std::istream& operator>>(std::istream& is, In2& obj) { T1 t1; T2 t2; is >> t1 >> t2; obj = {t1, t2}; return is; } }; template struct In3 { T1 a; T2 b; T3 c; friend std::istream& operator>>(std::istream& is, In3& obj) { T1 t1; T2 t2; T3 t3; is >> t1 >> t2 >> t3; obj = {t1, t2, t3}; return is; } }; template struct In4 { T1 a; T2 b; T3 c; T4 d; friend std::istream& operator>>(std::istream& is, In4& obj) { T1 t1; T2 t2; T3 t3; T4 t4; is >> t1 >> t2 >> t3 >> t4; obj = {t1, t2, t3, t4}; return is; } }; #ifdef LOCAL #include #else #define dump(...) ; #endif namespace { ll n; vector> va; void read() { cin >> n; take(va, n); } ll run() { vector dpx(n + 1), dpy(n + 1); for (int i : range(n)) { auto [xi, yi] = va[i]; ll xp = -1, yp = -1; if (i) { xp = va[i - 1].a; yp = va[i - 1].b; } dpx[i + 1] = max( dpx[i] + (xp == yi ? yi : 0LL), dpy[i] + (yp == yi ? yi : 0LL) ); dpy[i + 1] = max( dpx[i] + (xp == xi ? xi : 0LL), dpy[i] + (yp == xi ? xi : 0LL) ); } ll s = 0; for (auto [x, y] : va) if (x == y) s += x; return max(dpx[n], dpy[n]) + s; } } // namespace template void exec(F f) { if constexpr (std::is_same_v) f(); else cout << f() << endl; } int main(int argc, char** argv) { cerr << fixed << setprecision(12); cout << fixed << setprecision(12); int testcase = 1; if (argc > 1) testcase = atoi(argv[1]); while (testcase--) { read(); } exec(run); }