1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include<iostream> #include<vector> using namespace std; int N; vector<int>station[10010]; int change[10010][10010]; int start, dest; vector<int>temp; vector<int>path; bool flag[10010]; int mini = 100; void dfs(int s, int cnt, int preline) { if (s == dest) { cout << cnt << endl; if (path.empty() || temp.size() < path.size()) { path = temp; mini = cnt; } else { if (temp.size() == path.size() && cnt < mini) { path = temp; mini = cnt; } } return; } for (int i = 0; i < station[s].size(); i++) { if (!flag[station[s][i]]) { flag[station[s][i]] = true; temp.push_back(station[s][i]); if (change[s][station[s][i]] != preline) { dfs(station[s][i], cnt + 1, change[s][station[s][i]]); } else { dfs(station[s][i], cnt, preline); } flag[station[s][i]] = false; temp.pop_back(); } } } int main() { cin >> N; int sta,n; for (int i = 1; i <= N; i++) { cin >> n; cin >> sta; int pre = sta; for (int j = 0; j < n - 1; j++) { cin >> sta; station[pre].push_back(sta); station[sta].push_back(pre); change[sta][pre] = i; change[pre][sta] = i; pre = sta; } } cin >> n; for (int i = 0; i < n; i++) { cin >> start >> dest; fill(flag, flag + 10010, false); temp.clear(); path.clear(); temp.push_back(start); flag[start] = true; dfs(start, 0, 0); cout << path.size() - 1 << endl; int pre = change[path[0]][path[1]]; int first = path[0]; for (int j = 0; j < path.size()-1; j++) { if (change[path[j]][path[j + 1]] != pre) { printf("Take Line#%d from %04d to %04d.\n", pre, first, path[j]); first = path[j]; pre = change[path[j]][path[j + 1]]; } if(j+1== path.size() - 1) printf("Take Line#%d from %04d to %04d.\n", pre, first, path[j+1]); } } }
|