#P2507. [SCOI2008] 配对

    ID: 3324 远端评测题 1000ms 125MiB 尝试: 0 已通过: 0 显示难度提高 上传者: 标签>动态规划 DP搜索2008四川各省省选

[SCOI2008] 配对

Problem 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 5∼85 \sim 8, 6∼56 \sim 5, 8∼78 \sim 7, with absolute differences 3,1,13, 1, 1, summing to 55. Note that 5∼55 \sim 5, 6∼76 \sim 7, 8∼88 \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: n≤104n \le {10}^4.
100%100 \% of the testdata satisfies: 1≤n≤1051 \le n \le {10}^5, AiA_i and BiB_i are integers between 11 and 109{10}^9.

Translated by ChatGPT 5