z[75][75];s,d,t,a,*p,j;main(i){for(;scanf("%d%d",&s,&d)*s;printf("%d\n",s)){for(memset(z,9,2e4);s--;)for(t=i=d+1;--i;a?*p=fmin(*p,a),*z[t]>*p?t=i:0:0)scanf("%d",&a),p=z[i];for(i=d;i;i--)for(s=i;--s;a?z[s][i]=z[i][s]=a:0)scanf("%d",&a);for(s=i=0;i++-d;t=a)for(s+=*z[t],*z[t]=0,a=j=d+1;--j;*p&&*z[a]>*p?a=j:0)p=z[j],*p=fmin(*p,p[t]);}}