#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]>(a[j][i]+a[i][k])) {
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;
if (l!=T){
cout<<'\n';
}
}
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCBULG4scix4LHk7CmludCBhWzEwMDBdWzEwMDBdOwppbnQgbWFpbigpCnsKCWNpbj4+VDsKCWZvciAoaW50IGw9MTsgbDw9VDsgbCsrKSB7CgkJY2luPj5uOwoKCQlmb3IgKGludCBqPTE7IGo8PW47IGorKykgewoJCQlmb3IoaW50IGsgPSAxOyBrIDw9IG47IGsrKykgewoJCQkJaW50IGNvc3Q7CgkJCQljaW4gPj4gY29zdDsKCQkJCWFbal1ba10gPSBjb3N0OwoJCQl9CgoJCX0KCgkJZm9yIChpbnQgaT0xOyBpPD1uOyBpKyspIHsKCQkJZm9yIChpbnQgaj0xOyBqPD1uOyBqKyspIHsKCQkJCWZvciAoaW50IGs9MTsgazw9bjsgaysrKSB7CgkJCQkJaWYgKGFbal1ba10+KGFbal1baV0rYVtpXVtrXSkpIHsKCQkJCQkJYVtqXVtrXT1hW2pdW2ldK2FbaV1ba107CgkJCQkJCS8vYVtrXVtqXT1hW2pdW2ldK2FbaV1ba107CgkJCQkJfQoJCQkJfQoJCQl9CgkJfQoJCWNpbiA+PiByOwoJCWludCBzPTA7CgkJZm9yIChpbnQgaT0xOyBpPD1yOyBpKyspIHsKCQkJY2luPj54Pj55OwoJCQlzKz1hW3hdW3ldOwoJCX0KCQljb3V0PDwiQ2FzZSAjIjw8bDw8IjogIjw8czsKCQlpZiAobCE9VCl7CgkJICAgIGNvdXQ8PCdcbic7CgkJfQoJfQp9Cg==