注意输出有格式要求。
个人感觉用BFS也可以做出来,有空试试。。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n,kase=0;
while(scanf("%d",&n)!=EOF)
{
int dist[25][25];
for(int i=0; i<25; ++i)
for(int j=0; j<25; ++j)
dist[i][j]=1000000000;
int t;
for(int i=0; i<n; ++i)
{
scanf("%d",&t);
dist[1][t]=dist[t][1]=1;
}
for(int i=2; i<20; ++i)
{
scanf("%d",&n);
for(int j=0; j<n; ++j)
{
scanf("%d",&t);
dist[i][t]=dist[t][i]=1;
}
}
for(int i=0; i<=20; ++i)
dist[i][i]=0;
for(int k=1; k<=20; ++k)
for(int i=1; i<=20; ++i)
for(int j=1; j<=20; ++j)
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
printf("Test Set #%d\n",++kase);
int N;
scanf("%d",&N);
while(N--)
{
int st,ed;
scanf("%d%d",&st,&ed);
printf("%2d to %2d: %d\n",st,ed,dist[st][ed]);
}
printf("\n");
}
return 0;
}