1 #include<cstdio>
2 #include<cstdlib>
3 #include<cstring>
4 #include<cmath>
5 #include<iostream>
6 #include<algorithm>
7 using namespace std;
8 const int N = 1005;
9 const int inf = 0x3f3f3f3f;
10 typedef long long LL;
11 int vis[N], ac[N], n;
12 int as[N][N], dis[N], pre[N];
13 void init()
14 {
15 memset(vis, 0, sizeof(vis));
16 memset(dis, 0, sizeof(dis));
17 memset(pre, 0, sizeof(pre));
18 for(int i = 0; i < N; i++)
19 for(int j = 0; j < N; j++)
20 if(i == j) as[i][j] = 0;
21 else as[i][j] = inf;
22 }
23 LL prime()
24 {
25 int i, j, index;
26 LL mini, ans = 0;
27 for(i = 1; i < n; i++)
28 {
29 mini = inf;
30 for(j = 1; j <= n; j++)
31 {
32 if(vis[j] == 0 && dis[j] < mini)
33 {
34 mini = dis[j];
35 index = j;
36 }
37 }
38 vis[index] = 1;
39 //ans += ac[index] + ac[pre[index]];
40 for(j = 1; j <= n; j++)
41 {
42 if(vis[j] == 0 && dis[j] > as[index][j])
43 {
44 dis[j] = as[index][j];
45 pre[j] = index;
46 }
47 }
48 }
49 for(i = 1; i <= n; i++)
50 ans += dis[i];
51 return ans;
52 }
53 int main()
54 {
55 int i, j, t;
56 LL ans;
57 scanf("%d", &t);
58 while(t--)
59 {
60 init();
61 scanf("%d", &n);
62 for(i = 1; i <= n; i++)
63 scanf("%d", &dis[i]);
64
65 for(i = 1; i <= n; i++)
66 for(j = 1; j <= n; j++)
67 {
68 scanf("%d", &as[i][j]);
69 //as[i][j] += ac[i];
70 // as[i][j] += ac[j];
71 }
72 ans = prime();
73 printf("%lld\n", ans);
74 }
75 return 0;
76 }