#include <bits/stdc++.h>
using namespace std;

struct node{
	int x,y,len;	
}; 


int f[110];
node a[10010];
int t,k = 0;
int n,q;

int find(int x){
	return x == f[x]?x:f[x] = find(f[x]);
}

void merge(int x,int y){
	int fx = find(x);
	int fy = find(y);
	if(fx != fy){
		f[fx] = fy;
	}
}

bool cmp(node n1,node n2){
	return n1.len < n2.len;
}

int main() {
	cin>>n;
	for(int i = 1;i <= n;i++){
		for(int j = 1;j <= n;j++){
			cin>>t;
			if(i > j){
				k++;
				a[k].x = i;
				a[k].y = j;
				a[k].len = t;		
			}		
		}
	}
	
	for(int i = 1;i <= n;i++){
		f[i] = i;
	} 
	
	sort(a+1,a+k+1,cmp);
	cin>>q;
	int x,y;
	int c = 0;
	for(int i = 1;i <= q;i++){
		cin>>x>>y;
		if(find(x) != find(y)){
			c++;
			merge(x,y);
		}
	}
	
	if(c >= n - 1){
		cout<<0;
		return 0;
	}
	
	int s = 0;
	for(int i = 1;i <= k;i++){
		if(find(a[i].x) != find(a[i].y)){
			merge(a[i].x,a[i].y);
			c++;
			s = s + a[i].len;
		}
		
		if(c == n - 1){
			cout<<s;
			break;
		}
	}
}


/**************************************************************
	Problem: 2070
	User: admin
	Language: C++
	Result: Accepted
	Time:57 ms
	Memory:2196 kb
****************************************************************/