20250520 字典序最小的拓扑排序

求字典序最小的拓扑排序

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<string> lexicographicallySmallestTopologicalSort(unordered_map<string, vector<string>>& graph) {
    unordered_map<string, int> inDegree;
    
    // 首先,初始化所有节点的入度为0
    for (const auto& p : graph) {
        inDegree[p.first] = 0;
    }
    
    // 然后,计算每个节点的实际入度
    for (const auto& p : graph) {
        for (const string& neighbor : p.second) {
            inDegree[neighbor]++;
        }
    }

    priority_queue<string, vector<string>, greater<string>> pq;
    for (const auto& p : inDegree) {
        if (p.second == 0) {
            pq.push(p.first);
        }
    }

    vector<string> result;
    while (!pq.empty()) {
        string node = pq.top();
        pq.pop();
        result.push_back(node);
        for (const string& neighbor : graph[node]) {
            inDegree[neighbor]--;
            if (inDegree[neighbor] == 0) {
                pq.push(neighbor);
            }
        }
    }

    return result;
}

int main() {
    unordered_map<string, vector<string>> graph = {
        {"A", {"C"}},
        {"E", {"C", "D"}},
        {"C", {"D"}},
        {"B", {"C"}}
    };

    vector<string> result = lexicographicallySmallestTopologicalSort(graph);
    for (const string& node : result) {
        cout << node << " ";
    }
    cout << endl;

    return 0;
}
  • 首先初始化所有在 graph 中的节点的入度为 0
  • 然后计算每个节点的实际入度
  • 这样可以确保所有节点都被正确初始化,包括那些只作为后继节点的节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值