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

#FW0000110. Geonosis (Geonosis)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Geonosis (Geonosis)

Geonosis

Source: UVa

Version: Phuoc Hung OJ Extended

Problem Statement

A complex has nn communication towers with directed communication costs given by matrix ww. Towers are destroyed in permutation order pp. Before each destruction, the required energy is the sum of shortest-path distances over all ordered pairs (u,v)(u,v) of distinct surviving towers; destroyed towers may not be used as intermediates. Compute the total energy over the full process.

Input

First nn, then an n×nn\times n matrix ww with wii=0w_{ii}=0, then a permutation pp of 0,…,n−10,\ldots,n-1 giving destruction order.

Output

Print the total energy as a 64-bit integer.

Subtasks

  • Subtask 1 (40 points): 1≤n≤5,  1≤wij≤100 (i≠j)1\le n\le 5,\;1\le w_{ij}\le 100\ (i\ne j). All input-format and graph conditions above apply.

  • Subtask 2 (60 points): 1≤n≤18,  1≤wij≤10000 (i≠j)1\le n\le 18,\;1\le w_{ij}\le 10000\ (i\ne j). All input-format and graph conditions above apply.

Examples

Input

2
0 3
2 0
0 1

Output

5

Explanation

Initially both towers are active: distance 0 to 1 is 3 and 1 to 0 is 2, totaling 5. After tower 0 is removed, no pair of distinct active towers remains. The overall total is 5.