本文共 2276 字,大约阅读时间需要 7 分钟。
这道题目要求我们根据输入的北京地铁线路数据,找到用户的起始位置到目标位置的最短换乘次数,并输出最优路径。我们可以通过广度优先搜索(BFS)计算最短路径,然后用深度优先搜索(DFS)重建路径,最后输出结果。
#includeusing namespace std;unordered_map lines;vector > trans, tempTrans;vector grap[10005], past[10005], path, temp, dis(10005);int n, m, k, start, dest;void BFS() { queue que; for (int i = 0; i < 10005; ++i) { past[i].clear(); dis[i] = INT_MAX; } que.push(start); dis[start] = 0; while (!que.empty()) { int q = que.front(); que.pop(); if (dis[q] > dis[dest]) continue; for (int g : grap[q]) { if (dis[g] >= dis[q] + 1) { if (dis[g] == INT_MAX) { que.push(g); } dis[g] = dis[q] + 1; if (dis[g] > dis[q] + 1) { past[g].clear(); } past[g].push_back(q); } } } } void DFS(int d) { path.push_back(d); if (d == start) { tempTrans.clear(); tempTrans.push_back({start, -1}); for (int i = path.size() - 2; i > 0; --i) { if (lines[path[i + 1] * 10000 + path[i]] != lines[path[i] * 10000 + path[i - 1]]) { tempTrans.push_back({path[i], lines[path[i] * 10000 + path[i + 1]]}); } } } tempTrans.push_back({dest, lines[path[1] * 10000 + dest]}); if (trans.size() > tempTrans.size() || trans.size() == 0) { trans = tempTrans; } for (int p : past[d]) { DFS(p); } path.pop_back(); } int main() { cin >> n; for (int i = 1; i <= n; ++i) { cin >> m; vector temp(m); for (int j = 0; j < m; ++j) { cin >> temp[j]; } for (int j = 1; j < m; ++j) { int s1 = temp[j]; int s2 = temp[j - 1]; lines[s1 * 10000 + s2] = i; lines[s2 * 10000 + s1] = i; grap[s1].push_back(s2); grap[s2].push_back(s1); } } cin >> k; for (int i = 0; i < k; ++i) { cin >> start >> dest; BFS(); path.clear(); trans.clear(); DFS(dest); cout << dis[dest] << endl; for (int i = 0; i < trans.size() - 1; ++i) { printf("Take Line#%d from %04d to %04d.\n", trans[i + 1].second, trans[i].first, trans[i + 1].first); } } return 0; }
grap和线路映射lines,记录每个站点所属的线路。通过以上步骤,可以高效地解决问题并输出符合要求的最短路径。
转载地址:http://yntuz.baihongyu.com/