PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#TP0000039. Ghép cặp bò (Paired Up)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Ghép cặp bò (Paired Up)

Paired Up

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

A farm has an even number MM of cows. They are described by NN groups: group ii contains cic_i cows, each with milk output viv_i. The viv_i values are pairwise distinct. All cows must be partitioned into M/2M/2 pairs. Milking a pair takes time equal to the sum of its members’ milk outputs, and all pairs are milked simultaneously. Minimize the maximum pair time.

Input

  • The first line contains NN, the number of groups.
  • Each of the next NN lines contains cic_i and viv_i: the count and milk output of cows in that group. The total M=∑ciM=\sum c_i is even.

Output

Print one integer: the minimum time to finish milking all pairs.

Subtasks

  • Subtask 1 (20 points): 1≤N≤81\le N\le8; 1≤ci1\le c_i; 1≤vi≤1091\le v_i\le10^9 for all 1≤i≤N1\le i\le N; viv_i pairwise distinct; M=∑i=1Nci≤109M=\sum_{i=1}^{N}c_i\le10^9 and MM even.
  • Subtask 2 (30 points): 1≤N≤20001\le N\le2000; 1≤ci1\le c_i; 1≤vi≤1091\le v_i\le10^9 for all 1≤i≤N1\le i\le N; viv_i pairwise distinct; M=∑i=1Nci≤109M=\sum_{i=1}^{N}c_i\le10^9 and MM even.
  • Subtask 3 (50 points): 1≤N≤1000001\le N\le100000; 1≤ci1\le c_i; 1≤vi≤1091\le v_i\le10^9 for all 1≤i≤N1\le i\le N; viv_i pairwise distinct; M=∑i=1Nci≤109M=\sum_{i=1}^{N}c_i\le10^9 and MM even.

Examples

Input

3
1 8
2 5
1 2

Output

10

Explanation

The outputs are 8,5,5,28,5,5,2. Pair 88 with 22 (time 1010) and the two cows of output 55 together (time 1010). Pairing output 88 with output 55 would take 1313. As output 88 must be paired with a cow of output at least 22, finishing in less than 1010 is impossible.