|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
×
如题,可运行,但是结果一直是10
正确的应该是x出现两次后被两个父节点共享,应该是20
但是一直找不到原因........
- #include <iostream>
- #include <vector>
- #include <memory>
- #include <functional>
- #include <unordered_map>
- #include <string>
- #include <algorithm>
- template<typename T>
- class Registry {
- std::unordered_map<std::string, std::function<T(const std::vector<std::string>&)>> creators;
- public:
- void add(const std::string& key, std::function<T(const std::vector<std::string>&)> fn) {
- creators[key] = fn;
- }
- T create(const std::string& key, const std::vector<std::string>& args) {
- auto it = creators.find(key);
- if (it == creators.end()) throw std::runtime_error("not found: " + key);
- return it->second(args);
- }
- };
- struct Node {
- std::string name;
- std::vector<std::shared_ptr<Node>> children;
- int weight;
- Node(std::string n, int w) : name(std::move(n)), weight(w) {}
- };
- class Builder {
- Registry<std::shared_ptr<Node>> reg;
- std::unordered_map<std::string, std::shared_ptr<Node>> pool;
- public:
- Builder() {
- reg.add("leaf", [](const std::vector<std::string>& a) {
- return std::make_shared<Node>(a[0], std::stoi(a[1]));
- });
- reg.add("group", [](const std::vector<std::string>& a) {
- return std::make_shared<Node>(a[0], 0);
- });
- }
- std::shared_ptr<Node> make(const std::string& type, const std::vector<std::string>& args) {
- auto n = reg.create(type, args);
- pool[n->name] = n;
- return n;
- }
- std::shared_ptr<Node> get(const std::string& name) {
- auto it = pool.find(name);
- return it == pool.end() ? nullptr : it->second;
- }
- void link(const std::string& parent, const std::string& child) {
- auto p = get(parent);
- auto c = get(child);
- if (p && c) p->children.push_back(c);
- }
- };
- int computeWeight(const std::shared_ptr<Node>& node, std::vector<std::string>& visited) {
- if (!node) return 0;
- if (std::find(visited.begin(), visited.end(), node->name) != visited.end())
- return 0;
- visited.push_back(node->name);
- int total = node->weight;
- for (auto& c : node->children) {
- total += computeWeight(c, visited);
- }
- return total;
- }
- int main() {
- Builder b;
- b.make("leaf", {"x", "10"});
- b.make("group", {"left", "0"});
- b.make("group", {"right", "0"});
- b.make("group", {"root", "0"});
- b.link("root", "left");
- b.link("root", "right");
- b.link("left", "x");
- b.link("right", "x");
- std::vector<std::string> visited;
- auto root = b.get("root");
- int result = computeWeight(root, visited);
- std::cout << result << std::endl;
- return 0;
- }
复制代码 |
|