【PAT甲级】1178 File Path(25分)[文件树,模拟,unordered_map]

问题思路:

  • 在不断输入的过程中,可以通过层深和一个二维的vector数组来建立一棵树。
  • 即每输入一个节点,应当作为该节点上一层的最后一个节点的子孩子。
  • 用一个哈希value来指定节点的id,通过一个last记录每个节点id(此时作为last的下标)的父节点是谁。
  • 事实上,这种溯源的思路在之前的这道题中也有体现,只不过那里是图,这里是树。【PAT甲级】1175 Professional Ability Test(30分)[dijkstra(优先队列),拓扑排序]

代码实现:

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

int n;
vector<string> last(1005);
unordered_map<string, int> value;

void buildTree() {
    vector<vector<string>> Tree(1005, vector<string>());    // 每一个节点作为每一层深的最后一个节点的子孩子
    int cnt = 0;
    cin >> n;
    cin.ignore(); // Clear the newline character from the input buffer

    for (int i = 0; i < n; i++) {
        string line;
        getline(cin, line);
        int depth = line.find_first_not_of(' '); // 层深
        string id = line.substr(depth, 4); // 节点字符串
        value[id] = cnt;
        Tree[depth].push_back(id);
        if (depth > 0) {
            last[cnt] = Tree[depth - 1].back();    // 每个节点记录上一层的父节点是谁
        }
        cnt += 1;
    }
    return ;
}

vector<string> findPath(const string& target) {
    vector<string> path;
    if (value.find(target)  == value.end()) return path;
    string now = target;
    while (now != "0000") {
        path.push_back(now);
        now = last[value[now]];
    }
    path.push_back("0000");
    return path;
}

int main() {
    buildTree();
    int k;
    cin >> k;

    for (int i = 0; i < k; i++) {
        string query;
        cin >> query;
        vector<string> path = findPath(query);
        if (!path.empty()) {
            for (int i = path.size() - 1; i >= 0; i--) {
                cout << path[i];
                i && printf("->");
            }
            printf("\n");
        } else {
            cout << "Error: " << query << " is not found." << endl;
        }
    }

    return 0;
}
相关推荐
abluckyboy9 分钟前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异14 分钟前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_7066532316 分钟前
分布式系统安全通信
开发语言·c++·算法
Zach_yuan31 分钟前
深入浅出 JSONCpp
linux·服务器·网络·c++
寻寻觅觅☆1 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx1 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
天天爱吃肉82181 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
alphaTao1 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
阿猿收手吧!2 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++