N叉树+附带值+dfs递归

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>

using namespace std;

// 定义树节点结构体
struct Node {
    string name;
    string parent;
    int severe_issues;
    int normal_issues;
    vector<Node*> children;
    Node(string n, string p, int s, int n_) : name(n), parent(p), severe_issues(s), normal_issues(n_) {}
};

// 计算遗留问题缺陷密度 DI 值
pair<int,int> calculateDI(Node* root) {
    if (!root)
        return { 0,0 };
    int total_severe = root->severe_issues;
    int total_normal = root->normal_issues;
    for (Node* child : root->children) {
        auto p = calculateDI(child);
        total_severe +=p.first;
        total_normal += p.second;
    }

    return { total_severe,total_normal };
}

bool countRiskServices(Node* root, int threshold) {
    if (!root)
        return 0;
    int risk_services = 0;
    auto p = calculateDI(root);
    int di_value = p.first*5+ p.second * 2;

    if (di_value > threshold)
        return true;
    else return false;
}

int main() {
    int threshold, N;
    cin >> threshold >> N;

    unordered_map<string, Node*> nodes;
    unordered_map<string, vector<Node*>> temp_children; // 存储未链接到父节点的子节点

    // 构建树结构
    for (int i = 0; i < N; ++i) {
        string A, B, C;
        int D;
        cin >> A >> B >> C >> D;
        if (nodes.count(A) == 0) {
            Node* node = new Node(A, B, (C == "0" ? D : 0), (C == "1" ? D : 0));
            nodes[A] = node;
            if (B != "*") {
                if (nodes.find(B) != nodes.end()) {
                    nodes[B]->children.push_back(node);
                }
                else {
                    temp_children[B].push_back(node);
                }
            }
        }
        else {
            if (C == "0")
                nodes[A]->severe_issues = D;
            if(C == "1")
                nodes[A]->normal_issues = D;
        }

    }

    for (const auto& entry : temp_children) {
        for (Node* child : entry.second) {
            nodes[entry.first]->children.push_back(child);
        }
    }
    int risk_services=0;
    Node* root = nullptr;
    for (const auto& entry : nodes) {
        if (entry.second->parent == "*") {
            root = entry.second;
            if(countRiskServices(root, threshold))
                risk_services++;
        }
    }

    
    cout << risk_services << endl;


    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值