#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<math.h>
#include<vector>
using namespace std;
#define maxn 105
int f[maxn];
struct node
{
int u, v, len;
friend bool operator < (node a, node b)
{
return a.len > b.len;
}
};
int Find(int x)
{
if(f[x] != x)
f[x] = Find(f[x]);
return f[x];
}
int main()
{
int N;
while(scanf("%d", &N) != EOF)
{
int M, u, v;
node s;
priority_queue<node> Q;
for(s.u=1; s.u<=N; s.u++)
{
f[s.u] = s.u;
for(s.v=1; s.v<=N; s.v++)
{
scanf("%d", &s.len);
Q.push(s);
}
}
scanf("%d", &M);
while(M--)
{
scanf("%d%d", &u, &v);
u = Find(u), v = Find(v);
f[u] = v;
}
int ans = 0;
while(Q.size())
{
s = Q.top();Q.pop();
u = Find(s.u), v = Find(s.v);
if(u != v)
{
f[u] = v;
ans += s.len;
}
}
printf("%d\n", ans);
}
return 0;
}