This page is still under construction.

Parts of this page are still being built. What you see may change.

Installations

Time limit1sMemory limit128 MB

Summary
Order jobs with given service times and deadlines to minimize the sum of the two largest lateness penalties.
Level

Hard8 of 10

Topics
Dynamic programming, Sorting, Greedy
Solved
No attempts yet

Problem

In the morning, a service engineer at a telecom company receives a list of jobs to carry out that day: installing telephones, internet, IPTV, and repairing existing facilities. Each job comes with a deadline by which the client wants it finished, but because of the workload the engineer cannot always meet every deadline.

The engineer works on one job at a time. Every job JiJ_i has a serving time sis_i and a deadline did_i. Starting from time 00, the jobs are carried out one after another in some order, and each job runs to completion once it starts. If JiJ_i finishes at time CiC_i, its penalty is max⁡(0,Ci−di)\max(0, C_i - d_i), that is, how far it runs past its deadline. All values are positive integers with 0<si≤di0 < s_i \le d_i.

Arrange the jobs so that the sum of the two largest penalties is as small as possible.

For example, take six jobs whose (si,di)(s_i, d_i) are (1,7),(4,7),(2,4),(2,15),(3,5),(3,8)(1, 7), (4, 7), (2, 4), (2, 15), (3, 5), (3, 8) for i=1,…,6i = 1, \dots, 6. Figure 1 shows a schedule that minimizes the sum of the two largest penalties. Here the two largest penalties belong to J2J_2 and J6J_6, equal to 66 and 11, so their sum is 77.

Figure 1: an optimal schedule for the example

Input

The first line contains the number of test cases TT.

Each test case begins with a line containing an integer nn (1≤n≤5001 \le n \le 500), the number of jobs. Each of the next nn lines contains two integers sis_i and did_i (1≤si≤di≤100001 \le s_i \le d_i \le 10000): the serving time and the deadline of job JiJ_i.

Output

For each test case, print a single line with the sum of the two largest penalties over an optimal schedule.

Examples5

  1. Example 1

    Input
    3
    6
    1 7
    4 7
    2 4
    2 15
    3 5
    3 8
    7
    2 17
    2 11
    3 4
    3 20
    1 20
    4 7
    5 14
    10
    2 5
    2 9
    5 10
    3 11
    3 4
    4 21
    1 7
    2 9
    2 11
    2 23
    
    Expected output
    7
    0
    14
    
  2. Example 2

    Input
    1
    1
    7 9
    
    Expected output
    0
    
  3. Example 3

    Input
    1
    2
    3 3
    3 3
    
    Expected output
    3
    
  4. Example 4

    Input
    1
    5
    1 50
    1 50
    1 50
    1 50
    1 50
    
    Expected output
    0
    
  5. Example 5

    Input
    1
    6
    1 7
    4 7
    2 4
    2 15
    3 5
    3 8
    
    Expected output
    7