#include <iostream>
using namespace std;
const int MAXN = 110;
int N, ans; //城市数量,最终输出
int city[MAXN][MAXN]; //城市之间的距离
int dis[MAXN]; //当前已达城市集合到剩余城市的最短距离
int vis[MAXN]; //已达城市
void prim() //prim算法
{
int min, index;
memset(vis, 0, sizeof(vis));
//从城市1开始,即开始时已达城市只有城市1
for (int i = 1; i <= N; i++)
{
dis[i] = city[1][i];
}
vis[1] = 1;
for (int i = 1; i <= N; i++)
{
min = INT_MAX;
//查找未达城市中,到达距离最短的城市
for (int j = 1; j <= N; j++)
{
if (!vis[j] && dis[j] < min)
{
index = j;
min = dis[j];
}
}
if (min == INT_MAX) //所有城市已达
break;
vis[index] = 1;
ans += dis[index];
//更新已达城市集合到达未达城市的最短距离
for (int j = 1; j <= N; j++)
{
if (!vis[j] && city[index][j] < dis[j])
dis[j] = city[index][j];
}
}
}
int main()
{
int Q, a, b;
while (cin >> N)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
cin >> city[i][j];
}
cin >> Q; //目前已有的Q条路
for (int i = 1; i <= Q; i++)
{
cin >> a >> b; //a,b两城市已经有路,不在考虑距离
city[a][b] = city[b][a] = 0;
}
ans = 0;
prim();
cout << ans << endl;
}
return 0;
}