【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;
}
相关推荐
chuhx36 分钟前
Stream API 对两个 List 进行去重操作
数据结构·windows·list
元亓亓亓3 小时前
Java后端开发day36--源码解析:HashMap
java·开发语言·数据结构
小邓儿◑.◑4 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
酷ku的森5 小时前
数据结构:链表
数据结构·链表
何其有幸.6 小时前
实验3-3 比较大小(PTA|C语言)
c语言·数据结构·算法
丶Darling.6 小时前
26考研 | 王道 | 数据结构笔记博客总结
数据结构·笔记·考研
杨筱毅6 小时前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
东阳马生架构7 小时前
Sentinel源码—8.限流算法和设计模式总结二
算法·设计模式·sentinel
老饼讲解-BP神经网络7 小时前
一篇入门之-评分卡变量分箱(卡方分箱、决策树分箱、KS分箱等)实操例子
算法·决策树·机器学习
hjjdebug7 小时前
c++中的enum变量 和 constexpr说明符
c++·enum·constexpr