#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define M 25000 #define maxn 100000000 struct node { int v1,v2; int dis; }s[M]; int cmp(const node a,const node b) { if(a.dis<b.dis) return 1; else return 0; } int father[M]; int main() { int n; while(scanf("%d",&n)>0) { //int m=(n*(n-1))/2; int cnt=0; for(int i=0;i<=n;i++) father[i]=i; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { int tmp; scanf("%d",&tmp); if(i==j) { s[cnt].v1=i; s[cnt].v2=j; s[cnt++].dis=maxn; } else { s[cnt].v1=i; s[cnt].v2=j; s[cnt++].dis=tmp; } } int q; scanf("%d",&q); while(q--) { int tmp,tmp1; scanf("%d%d",&tmp,&tmp1); s[cnt].v1=tmp; s[cnt].v2=tmp1; s[cnt++].dis=0; } sort(s,s+cnt,cmp); int j=0,ans=0; while(j<cnt) { int tmp=s[j].v1; int tmp1=s[j].v2; int s1=father[tmp]; int s2=father[tmp1]; if(s1!=s2) { ans+=s[j].dis; for(int i=0;i<=n;i++) if(s2==father[i]) father[i]=s1; } j++; } printf("%d ",ans); } return 0; }