#P2507. [SCOI2008] 配对

    ID: 1522 远端评测题 1000ms 125MiB 尝试: 0 已通过: 0 难度: 7 上传者: 标签>动态规划,dp搜索2008四川各省省选期望

[SCOI2008] 配对

Description

You are given nn integers AiA_i and nn integers BiB_i. You need to pair them, that is, each AiA_i is matched to exactly one Bp[i]B_{p[i]}. The goal is to minimize the sum of absolute differences over all pairs, but pairing two equal numbers is not allowed. For example, if A={5,6,8}A = \{5, 6, 8\} and B={5,7,8}B = \{5, 7, 8\}, then an optimal pairing is 585 \sim 8, 656 \sim 5, 878 \sim 7, with absolute differences 3,1,13, 1, 1, summing to 55. Note that 555 \sim 5, 676 \sim 7, 888 \sim 8 are not allowed because equal numbers may not be paired.

Input Format

The first line contains a positive integer nn. Then follow nn lines, each containing two integers AiA_i and BiB_i. It is guaranteed that all AiA_i are pairwise distinct, and all BiB_i are also pairwise distinct.

Output Format

Output a single integer, the minimum possible sum of absolute differences of the paired integers. If it is impossible to pair, output -1.

3
3 65
45 10
60 25

32

3
5 5
6 7
8 8

5

Hint

Constraints:
30%30 \% of the testdata satisfies: n104n \le {10}^4.
100%100 \% of the testdata satisfies: 1n1051 \le n \le {10}^5, AiA_i and BiB_i are integers between 11 and 109{10}^9.

Translated by ChatGPT 5