Hamiltonian Circuit

시간 제한1초메모리 제한2048 MB

요약
n개의 쌍 (a_i, b_i)가 주어질 때, 간선 i에서 j의 가중치가 |a_i - b_j|인 완전 유향 그래프에서 해밀턴 회로의 최대 가중치 합을 구한다.
난이도

어려움10점 중 8점

유형
그리디, 정렬, 동적 계획법
정답자
아직 제출이 없습니다

문제

You are given nn pairs of integers (a_i,b_i)(a\_i, b\_i).

Consider a weighted directed complete graph GG with nn vertices, where the weight of the edge from ii (1≤i≤n1 \leq i \leq n) to jj (1≤j≤n1 \leq j \leq n) is ∣a_i−b_j∣|a\_i - b\_j|.

Find a Hamiltonian circuit in GG such that the sum of weights of the edges it traverses is maximized, and output this maximum value.

입력

The first line of the input contains an integer nn (2≤n≤1052 \leq n \leq 10^5) representing the number of pairs.

Each of the next nn lines contains two integers a_ia\_i and b_ib\_i (0≤a_i,b_i≤1090 \leq a\_i, b\_i \leq 10^9) representing a single pair.

You may assume that all 2n2 n integers a_ia\_i and b_ib\_i are pairwise distinct.

출력

Print a line with a single integer: the maximum sum of weights of the Hamiltonian circuit.

힌트

In the example, consider the Hamiltonian circuit 1→2→3→11 \to 2 \to 3 \to 1, with edge weights ∣1−2∣+∣8−5∣+∣4−10∣=10|1-2| + |8-5| + |4-10| = 10. It can be proven that there is no Hamiltonian circuit with sum of weights exceeding 1010, so the answer is 1010.

예제1

  1. 예제 1

    입력
    3
    1 10
    8 2
    4 5
    
    예상 출력
    10