Security Company

Interview

Time limit2sMemory limit128 MB

Summary
Points lie on a line with travel times between neighbors; starting from point a and visiting every point, minimize the total first-arrival time over all points.
Level

Medium6 of 10

Topics
Dynamic programming, Greedy, Array, Prefix sum
Solved
No attempts yet

Problem

Myungwoo works for a security company and is responsible for patrolling, on foot, several stores near a subway station.

The area can be represented as a single line segment. Myungwoo's office and the stores are placed, from left to right, on points p1,p2,…,pNp_1, p_2, \dots, p_N on this segment. The office is at pap_a, and this point is the starting point s=pas = p_a. Myungwoo starts patrolling at ss and must visit every store pip_i at least once.

The time needed to travel between two adjacent points pip_i and pi+1p_{i+1} is t[pi,pi+1]t[p_i, p_{i+1}]. The waiting time ℓi\ell_i of point pip_i is the time elapsed from leaving the start ss until first arriving at pip_i. The waiting time ℓa\ell_a of the start s=pas = p_a itself is 00. Myungwoo must choose a patrol route that minimizes the sum of the waiting times of all stores.

For example, suppose there are 66 stores p1p_1 through p6p_6, the start is s=p3s = p_3, and t[p1,p2]=7t[p_1,p_2] = 7, t[p2,p3]=4t[p_2,p_3] = 4, t[p3,p4]=1t[p_3,p_4] = 1, t[p4,p5]=2t[p_4,p_5] = 2, t[p5,p6]=9t[p_5,p_6] = 9. If Myungwoo starts by walking right from ss, the waiting times ℓ4\ell_4 and ℓ5\ell_5 become 11 and 33. With a suitable patrol order the sum of the waiting times can be made 7171, and no method achieves a smaller sum.

Given the number of points NN and the travel times t[pi,pi+1]t[p_i, p_{i+1}] (i=1,…,N−1i = 1, \dots, N-1) between adjacent points, write a program that finds the minimum possible sum of the waiting times.

Input

The first line contains the number of test cases TT. Each test case is structured as follows.

  • The first line contains the number of stores NN (1≤N≤1001 \le N \le 100).
  • The second line contains the position of the starting point aa (1≤a≤N1 \le a \le N). The aa-th point pa=sp_a = s is the starting point.
  • Each of the next N−1N-1 lines, the ii-th of them, contains t[pi,pi+1]t[p_i, p_{i+1}] (1≤t[pi,pi+1]≤15 000 0001 \le t[p_i, p_{i+1}] \le 15\,000\,000).

Output

For each test case, print on its own line the minimum sum of the waiting times over all ways of patrolling every store.

Examples1

  1. Example 1

    Input
    2
    6
    3
    7
    4
    1
    2
    9
    9
    5
    96
    24
    6
    2
    1
    3
    12
    48
    
    Expected output
    71
    605