Problem:
D: Dangerous Tower

ICPC で良い成績を収めるには修行が欠かせない．うさぎは ICPC で勝ちたいので，今日も修行をすることにした．

今日の修行は，積み木を丁寧に積み上げることによって，決してミスタイピングをしないほどの手先の器用さを手に入れようというものである．せっかく積み木がたくさんあるので，高い塔を作ろう．

積み木は N 個あり，i 番目 (1 ≤ i ≤ N) の積み木は 1 × Ai × Bi の直方体の形をしている．長さ 1 の辺は奥行き方向に用いて，長さ Ai, Bi の辺を横方向と高さ方向に 1 つずつ割り当てることにした．積み木を積み上げるとき，上の段の積み木は下の段の積み木より横の長さが厳密に短くなければならない．積み木は好きな順番に使うことができ，また，使わない積み木があってもよい．このような制約下で，作ることが可能な最も高い塔を作りたい．

Input

N
A1 B1
...
AN BN

1 ≤ N ≤ 1,000，1 ≤ Ai，Bi ≤ 1,000,000 を満たす．入力の値はすべて整数である．

Output

塔の高さの最大値を 1 行に出力せよ．

Sample Input 1

3
10 40
10 40
20 30

Sample Output 1

80

Sample Input 2

4
1 2
2 3
3 4
4 1

Sample Output 2

11

Solution in C# (judge verdict: Accepted)

using System;
using System.Linq;
using System.Collections.Generic;
using Debug = System.Diagnostics.Trace;
using SB = System.Text.StringBuilder;
using Number = System.Int64;
using C = System.Int32;
using V = System.Int32;
namespace Program
{
    public class Solver
    {
        public void Solve()
        {
            var n = ri;
            var a = new int[n];
            var b = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = ri;
                b[i] = ri;
            }
            var xs = a.Concat(b).Distinct().ToList(); xs.Sort();
            var N = xs.Count;
            var G = new MinCostFlow(n + N + 2);
            var src = n + N;
            var sink = src + 1;
            for (int i = 0; i < n; i++)
            {
                G.AddDirectedEdge(src, i, 1, 0);
                var p = xs.BinarySearch(a[i]);
                var q = xs.BinarySearch(b[i]);
                G.AddDirectedEdge(i, n + p, 1, -xs[q]);
                G.AddDirectedEdge(i, n + q, 1, -xs[p]);
            }
            for (int i = 0; i < N; i++)
                G.AddDirectedEdge(n + i, sink, 1, 0);
            var fv = G.Execute(src, sink);
            Debug.WriteLine(fv);
            Console.WriteLine(-fv.Value);
        }
        const long INF = 1L << 60;
        //int[] dx = { -1, 0, 1, 0 };
        //int[] dy = { 0, 1, 0, -1 };
        //*
        int ri { get { return sc.Integer(); } }
        long rl { get { return sc.Long(); } }
        double rd { get { return sc.Double(); } }
        string rs { get { return sc.Scan(); } }
        //*/

        public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
        static T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }
        static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
    }
}

#region main
static class Ex
{
    static public string AsString(this IEnumerable<char> ie) { return new string(ie.ToArray()); }
    static public string AsJoinedString<T>(this IEnumerable<T> ie, string st = " ")
    {
        return string.Join(st, ie.Select(x => x.ToString()).ToArray());
        //return string.Join(st, ie);
    }
    static public void Main()
    {
        Console.SetOut(new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var solver = new Program.Solver();
        solver.Solve();
        Console.Out.Flush();
    }
}
#endregion
#region Ex
namespace Program.IO
{
    using System.IO;
    using System.Text;
    using System.Globalization;
    public class Printer: StreamWriter
    {
        public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
        public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
    }
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        public readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) return 0;
            if (ptr >= len) { ptr = 0; if ((len = str.Read(buf, 0, 1024)) <= 0) { isEof = true; return 0; } }
            return buf[ptr++];
        }
        public char Char() { byte b = 0; do b = read(); while ((b < 33 || 126 < b) && !isEof); return (char)b; }

        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public string ScanLine()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b != '\n' && b != 0; b = (char)read())
                if (b != '\r') sb.Append(b);
            return sb.ToString();
        }
        public long Long() { return isEof ? long.MinValue : long.Parse(Scan()); }
        public int Integer() { return isEof ? int.MinValue : int.Parse(Scan()); }
        public double Double() { return isEof ? double.NaN : double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
}
#endregion



/// <summary>
/// ????????????????????????????°??????¨???????±????????????¨??????????????°????????§??????
/// </summary>
public class MinCostFlow
{
    bool hasng;
    readonly List<Edge>[] G;
    /// <summary>
    /// ????????° <paramref name="V"/> ??§???????????¨???????????°??????????§????????????????
    /// </summary>
    /// <param name="V">???????????°</param>
    /// <remarks>??????????????? O(<paramref name="V"/>) ??§?????????????????????</remarks>
    public MinCostFlow(int V)
    {
        G = new List<Edge>[V];
        for (int i = 0; i < V; i++)
            G[i] = new List<Edge>();

    }
    /// <summary>
    /// ?????? <paramref name="from"/> ???????????? <paramref name="to"/> ???????????? <paramref name="cap"/> ???????????? <paramref name="cost"/> ?????????????????????????????????
    /// </summary>
    /// <param name="from">?§??????¨??????????????? 0-indexed ??§?????????</param>
    /// <param name="to">????????¨??????????????? 0-indexed ??§?????????</param>
    /// <param name="cap">????????????</param>
    /// <param name="cost">???????????????</param>
    /// <remarks>??????????????? O(1) ??§?????????????????????</remarks>
    public void AddDirectedEdge(int from, int to, C cap, V cost)
    {
        addEdge(from, to, cap, 0, cost);
    }

    /// <summary>
    /// ?????? <paramref name="src"/> ???????????? <paramref name="sink"/> ????????§??§?????? <paramref name="f"/> ??????????°??????¨???????????????????????????
    /// </summary>
    /// <param name="src">???????????¨??????????????? 0-indexed ??§?????????</param>
    /// <param name="sink">???????????¨??????????????? 0-indexed ??§?????????</param>
    /// <param name="f">?????????????????????????????¨???????????§????????????-1?????????????????´??????????°??????¨?????§???????±??????????</param>
    /// <param name="inf">?????????????????????????????§????????¢????????§???</param>
    /// <remarks>???????????????Primal Dual???????????\?????????????¨??????? O(VE + FE log V) ??§?????????????????????V??????????????°???E???????????°???F??????????????¨????????????</remarks>
    public KeyValuePair<C, V> Execute(int src, int sink, C f = C.MaxValue, V inf = V.MaxValue / 3)
    {
        var n = G.Length;
        var dist = new V[n];
        var prev = new int[n];
        var prevEdge = new Edge[n];
        var potential = new V[n];


        C flow = 0;
        V cost = 0;
        var first = hasng;
        while (f > 0)
        {
            for (int i = 0; i < G.Length; i++)
                dist[i] = inf;

            //shortest path
            if (first)//spfa
            {
                var q = new Queue<int>();
                q.Enqueue(src); dist[src] = 0;
                var inQ = new bool[n];
                while (q.Count > 0)
                {
                    var p = q.Dequeue();
                    inQ[p] = false;
                    foreach (var e in G[p])
                    {
                        var t = e.To;
                        var d = dist[p] + e.Cost;
                        if (e.Cap > 0 && d < dist[t])
                        {
                            if (!inQ[t])
                            {
                                inQ[t] = true;
                                q.Enqueue(t);
                            }
                            dist[t] = d; prev[t] = p; prevEdge[t] = e;
                        }
                    }
                }
                first = false;
            }
            else//dijkstra
            {
                var vis = new bool[n];
                var pq = new PriorityQueue<KeyValuePair<int, V>>((l, r) => l.Value.CompareTo(r.Value));
                pq.Enqueue(new KeyValuePair<int, V>(src, 0));
                dist[src] = 0;
                while (pq.Count > 0)
                {
                    var p = pq.Dequeue().Key;
                    if (vis[p]) continue;
                    vis[p] = true;
                    foreach (var e in G[p])
                    {
                        if (e.Cap <= 0) continue;
                        var t = e.To;
                        if (vis[t]) continue;
                        var d = dist[p] + e.Cost + potential[p] - potential[t];
                        if (dist[t] > d)
                        {
                            dist[t] = d; prev[t] = p; prevEdge[t] = e;
                            pq.Enqueue(new KeyValuePair<int, V>(t, d));
                        }
                    }
                }


            }


            //update
            {
                if (dist[sink] == inf) break;
                for (int i = 0; i < n; i++)
                    potential[i] = Math.Min(inf, potential[i] + dist[i]);
                C df = f;
                V d = 0;
                for (var v = sink; v != src; v = prev[v])
                {
                    var e = prevEdge[v];
                    df = Math.Min(df, e.Cap); d += e.Cost;
                }
                if (d > 0) break;
                f -= df; cost += df * d; flow += df;
                for (var v = sink; v != src; v = prev[v])
                {
                    var e = prevEdge[v];
                    e.Cap -= df; e.Rev.Cap += df;
                }
            }

        }
        return new KeyValuePair<C, V>(flow, cost);
    }
    void addEdge(int f, int t, C c1, C c2, V e)
    {
        if (e < 0) hasng = true;
        var a = new Edge(t, c1, e);
        var b = new Edge(f, c2, -e);
        Edge.Link(a, b);
        G[f].Add(a);
        G[t].Add(b);
    }
    class Edge
    {
        public static void Link(Edge e1, Edge e2)
        {
            e1.Rev = e2; e2.Rev = e1;
        }
        public int To { get; private set; }
        public Edge Rev { get; private set; }
        public V Cost { get; private set; }
        public C Cap { get; set; }
        public Edge(int t, C c, V e)
        {
            To = t;
            Cap = c;
            Cost = e;
        }
        public override string ToString()
        {
            return string.Format("to: {0}, cap: {1}", To, Cap);
        }
    }
}
#region BinaryHeap
public class PriorityQueue<T>
{
    readonly List<T> heap = new List<T>();
    readonly Comparison<T> compare;
    public PriorityQueue() { compare = Comparer<T>.Default.Compare; }

    public PriorityQueue(Comparison<T> comparison) { compare = comparison; }
    public PriorityQueue(IComparer<T> comparer) { compare = comparer.Compare; }

    public void Enqueue(T item)
    {
        var pos = heap.Count;
        heap.Add(item);
        while (pos > 0)
        {
            var par = (pos - 1) / 2;
            if (compare(heap[par], item) <= 0)
                break;
            heap[pos] = heap[par];
            pos = par;
        }
        heap[pos] = item;

    }

    public T Dequeue()
    {
        var ret = heap[0];
        var pos = 0;
        var x = heap[heap.Count - 1];

        while (pos * 2 + 1 < heap.Count - 1)
        {
            var lch = pos * 2 + 1;
            var rch = pos * 2 + 2;
            if (rch < heap.Count - 1 && compare(heap[rch], heap[lch]) < 0) lch = rch;
            if (compare(heap[lch], x) >= 0)
                break;
            heap[pos] = heap[lch];
            pos = lch;
        }
        heap[pos] = x;
        heap.RemoveAt(heap.Count - 1);
        return ret;

    }
    public T Peek() { return heap[0]; }
    public int Count { get { return heap.Count; } }
    public bool Any() { return heap.Count > 0; }

    public T[] Items
    {
        get
        {
            var ret = heap.ToArray();
            Array.Sort(ret, compare);
            return ret;
        }
    }
}
#endregion