Kruskal
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=120;
int fa[maxn];
int n;
struct node
{
int s,t;
double w;
} edge[maxn*maxn];
int find(int x)
{
if(fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
int cmp(const node &a,const node &b)
{
return a.w<b.w;
}
void init()
{
for(int i=1; i<=n; i++) fa[i]=i;
}
int main()
{
int d,i,j,a,b,tot,ans,q;;
while(~scanf("%d",&n))
{
tot=0;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
scanf("%d",&d);
if(i!=j)
{
edge[tot].s=i;
edge[tot].t=j;
edge[tot].w=d;
tot++;
}
}
}
scanf("%d",&q);
while(q--)
{
scanf("%d%d",&a,&b);
for(i=0; i<tot; i++)
{
if(edge[i].s==a&&edge[i].t==b) edge[i].w=0;
if(edge[i].t==a&&edge[i].s==b) edge[i].w=0;
}
}
int ans=0;
init();
sort(edge,edge+tot,cmp);
for(i=0; i<tot; i++)
{
int u=find(edge[i].s);
int v=find(edge[i].t);
if(u!=v)
{
fa[u]=v;
ans+=edge[i].w;
}
}
printf("%d\n",ans);
}
return 0;
}