Problem:
Score : 700 points

Problem Statement

We have a directed weighted graph with N vertices.
Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i.

In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y).

We will consider a directed cycle in this graph that visits every vertex exactly once.
Find the minimum total weight of the edges in such a cycle.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the minimum total weight of the edges in such a cycle.

Sample Input 1

3
1 5
4 2
6 3

Sample Output 1

7

Consider the cycle 1→3→2→1. The weights of those edges are {\rm min}(A_1,B_3)=1, {\rm min}(A_3,B_2)=2 and {\rm min}(A_2,B_1)=4, for a total of 7.
As there is no cycle with a total weight of less than 7, the answer is 7.

Sample Input 2

4
1 5
2 6
3 7
4 8

Sample Output 2

10

Sample Input 3

6
19 92
64 64
78 48
57 33
73 6
95 73

Sample Output 3

227

Solution in Rust (1.15.1) (judge verdict: Accepted)

use std::io::Read;

fn run() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.trim().split_whitespace();
    let n: usize = it.next().unwrap().parse().unwrap();
    let mut a = vec![0u64; n];
    let mut b = vec![0u64; n];
    let mut e = vec![];
    for i in 0..n {
        a[i] = it.next().unwrap().parse().unwrap();
        b[i] = it.next().unwrap().parse().unwrap();
        e.push((a[i], 1, i));
        e.push((b[i], 2, i));
    }
    e.sort_by_key(|e| e.0);
    let mut set = vec![std::collections::BTreeSet::new(); 4];
    for i in 0..n {
        set[0].insert(i);
    }
    let mut sum = 0;
    for i in 0..n {
        let (c, b, k) = e[i];
        sum += c;
        for j in (0..3).rev() {
            if set[j].contains(&k) {
                set[j].remove(&k);
                set[j | b].insert(k);
            }
        }
    }
    if !set[0].is_empty() || set[1].len() == n || set[2].len() == n {
        println!("{}", sum);
        return;
    }
    let mut ans = std::u64::MAX;
    for &(c, _, k) in &e[n..(n + 2)] {
        for &u in &set[1] {
            if u != k || set[1].len() == 1 {
                ans = std::cmp::min(ans, sum - a[u] + c);
            }
        }
        for &u in &set[2] {
            if u != k || set[2].len() == 1 {
                ans = std::cmp::min(ans, sum - b[u] + c);
            }
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}