#include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include <cstring> using namespace std; int ma[25][25]; int d[25]; int vis[25]; int fun(int x,int y){ queue<int> que; que.push(x); vis[x] = 1; d[x] = 0; while(1){ int tm = que.front(); que.pop(); for(int i = 1;i <= 20;i++){ if(ma[tm][i] && !vis[i]){ if(i == y) { return d[tm] + 1; } else{ vis[i] = 1; d[i] = d[tm]+1; que.push(i); } } } } } int main(){ int n; int q = 1; while(cin >> n){ memset(ma,0,sizeof(ma)); for(int i = 0;i < n;i++){ int y; cin >> y; ma[1][y] = 1; ma[y][1] = 1; } for(int i = 2;i < 20;i++){ cin >> n; for(int j = 0;j < n;j++){ int y; cin >> y; ma[i][y] = 1; ma[y][i] = 1; } } int m; cin >> m; printf("Test Set #%d\n",q++); for(int i = 0;i < m;i++){ int x,y; cin >> x >> y; memset(vis,0,sizeof(vis)); memset(d,0,sizeof(d)); printf("%2d to %2d: %d\n",x,y,fun(x,y)); } cout << endl; } return 0; }
原文地址:http://blog.csdn.net/qq_24667639/article/details/45750419