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

#FW0000076. Bảo vệ vương quốc Rohan (Defend the Rohan)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Bảo vệ vương quốc Rohan (Defend the Rohan)

Defend the Rohan

Source: SPOJ

Version: Phuoc Hung OJ Extended

Problem Statement

Given a directed complete matrix of army-movement costs between nn stations and qq relocation orders (s,t)(s,t), compute the minimum total travel cost by allowing intermediate stations.

Input

First nn, then an n×nn\times n nonnegative directed cost matrix with zero diagonal, then qq orders s,ts,t (1-based).

Output

Print the minimum total relocation cost.

Subtasks

  • Subtask 1 (40 points): 2≤n≤7, 1≤q≤122\le n\le 7,\ 1\le q\le 12. 0≤Aij≤1060\le A_{ij}\le10^6, Aii=0A_{ii}=0, 1≤s,t≤n1\le s,t\le n; ma trận có hướng.

  • Subtask 2 (60 points): 2≤n≤30, 1≤q≤302\le n\le 30,\ 1\le q\le 30. 0≤Aij≤1060\le A_{ij}\le10^6, Aii=0A_{ii}=0, 1≤s,t≤n1\le s,t\le n; ma trận có hướng.

Examples

Input

3
0 1 5
1 0 2
5 2 0
2
1 3
3 1

Output

6

Explanation

The cheapest route 1→3 is 1→2→3 of cost 3; the opposite order also costs 3. The two relocation orders sum to 6.