#include <bits/stdc++.h>
using namespace std;
int T,n,r,x,y;
int a[1000][1000];
int main()
{
cin>>T;
for (int l=1;l<=T;l++){
cin>>n;
for (int j=1; j<=n; j++) {
for(int k = 1; k <= n; k++){
int cost;
cin >> cost;
a[j][k] = cost;
}
}
for (int i=1; i<=n; i++) {
for (int j=1;j<=n;j++){
for (int k=1;k<=n;k++){
if (a[j][k]==0 && j!=k){
a[j][k]=100000;
}
if (a[j][k]>(a[j][i]+a[i][k]) && a[j][i]!=100000 && a[i][k]!=100000){
a[j][k]=a[j][i]+a[i][k];
//a[k][j]=a[j][i]+a[i][k];
}
}
}
}
cin >> r;
int s=0;
for (int i=1;i<=r;i++){
cin>>x>>y;
s+=a[x][y];
}
cout<<"Case #"<<l<<": "<<s<<'\n';
}
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCBULG4scix4LHk7CmludCBhWzEwMDBdWzEwMDBdOwppbnQgbWFpbigpCnsKCWNpbj4+VDsKCWZvciAoaW50IGw9MTtsPD1UO2wrKyl7CgljaW4+Pm47CgkKCWZvciAoaW50IGo9MTsgajw9bjsgaisrKSB7CgkgICAgZm9yKGludCBrID0gMTsgayA8PSBuOyBrKyspewoJICAgICAgICBpbnQgY29zdDsKCSAgICAgICAgY2luID4+IGNvc3Q7CgkgICAgICAgIGFbal1ba10gPSBjb3N0OwoJICAgIH0KCSAgICAKCQl9CiAgICAKCWZvciAoaW50IGk9MTsgaTw9bjsgaSsrKSB7CiAgICAgICAgZm9yIChpbnQgaj0xO2o8PW47aisrKXsKICAgICAgICAgICAgZm9yIChpbnQgaz0xO2s8PW47aysrKXsKICAgICAgICAgICAgICAgIGlmIChhW2pdW2tdPT0wICYmIGohPWspewogICAgICAgICAgICAgICAgICAgIGFbal1ba109MTAwMDAwOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgaWYgKGFbal1ba10+KGFbal1baV0rYVtpXVtrXSkgJiYgYVtqXVtpXSE9MTAwMDAwICYmIGFbaV1ba10hPTEwMDAwMCl7CiAgICAgICAgICAgICAgICAgICAgYVtqXVtrXT1hW2pdW2ldK2FbaV1ba107CiAgICAgICAgICAgICAgICAgICAgLy9hW2tdW2pdPWFbal1baV0rYVtpXVtrXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0KCX0KCWNpbiA+PiByOwogICAgaW50IHM9MDsKICAgIGZvciAoaW50IGk9MTtpPD1yO2krKyl7CiAgICBjaW4+Png+Pnk7CiAgICAgcys9YVt4XVt5XTsgICAKICAgIH0KICAgIGNvdXQ8PCJDYXNlICMiPDxsPDwiOiAiPDxzPDwnXG4nOwoJfQp9Cg==