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,j=++d,2e4);s--;)for(i=d;--i;a&&*p>a?*p=a,*z[t]>a?t=i:0:0)scanf("%d",&a),p=z[i];for(;--j;)for(s=j;--s;a?z[s][j]=z[j][s]=a:0)scanf("%d",&a);for(s=i=0;d+~i++;t=a)for(s+=*z[t],*z[t]=0,a=j=d;--j;*p&&*z[a]>*p?a=j:0)p=z[j],*p=fmin(*p,p[t]);}}