1 条题解
-
0
解题思路:
- 可以将每个步骤看作图中的节点,连续步骤之间的关系看作有向边。这样,路线重建问题就转化为在有向图中寻找一条拓扑排序的路径。
- 由于每个步骤的入度和出度都相对简单,我们可以通过统计每个节点的入度,找到入度为 0 的节点作为起始节点,然后按照边的指向依次遍历后续节点,从而得到正确的路线顺序。 实现步骤
- 初始化:创建一个数据结构来存储节点和边的信息,同时记录每个节点的入度。
- 构建图:根据输入的连续步骤对,构建有向图,并更新节点的入度。
- 寻找起始节点:遍历所有节点,找到入度为 0 的节点,作为路线的起始点。
- 拓扑排序:从起始节点开始,按照边的指向依次访问下一个节点,并将访问过的节点从图中移除(即减少其后续节点的入度),重复这个过程,直到所有节点都被访问。
- 输出结果:按照拓扑排序的顺序输出节点,即重建的路线。
代码:
#include <iostream> #include <vector> #include <unordered_map> #include <queue> using namespace std; void reconstructRoute() { int scenario; cin >> scenario; for (int s = 1; s <= scenario; s++) { int steps; cin >> steps; unordered_map<string, vector<string>> graph; unordered_map<string, int> inDegree; vector<string> route; // 构建图和统计入度 for (int i = 0; i < steps - 1; i++) { string start, end; cin >> start >> end; graph[start].push_back(end); inDegree[end]++; if (inDegree.find(start) == inDegree.end()) { inDegree[start] = 0; } } // 寻找入度为0的起始节点 queue<string> startNodes; for (auto it : inDegree) { if (it.second == 0) { startNodes.push(it.first); } } // 拓扑排序 while (!startNodes.empty()) { string current = startNodes.front(); startNodes.pop(); route.push_back(current); for (string next : graph[current]) { inDegree[next]--; if (inDegree[next] == 0) { startNodes.push(next); } } } // 输出结果 cout << "Scenario #" << s << ":" << endl; for (string step : route) { cout << step << endl; } cout << endl; } } int main() { reconstructRoute(); return 0; }
- 1
信息
- ID
- 1492
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 6
- 已通过
- 1
- 上传者