拓扑排序

/*
 * 多行字符串,每个字符串格式为 xx -> yyy zzz ccc
 * 输出最小字典序拓扑结构
 */
int main(){
    
    map<string, set<string> > graph;
    map<string, int> indegree;
    
    string line;
    string target;
    stringstream sstr;
    
    while (getline (cin, line)){
        sstr.clear();
        sstr.str(line);
        string left, arrow, right;
        sstr >> left >> arrow;
        if (target.empty()){
            target = left;
        }
        indegree[left] += 0;
        while (sstr >> right){
            graph[left].insert(right);
            ++indegree[right];
        }
    }
    set<string> zeroIndegree;
    vector<string> path;
    zeroIndegree.insert(target);
    while (!zeroIndegree.empty()){
        string vertex = *zeroIndegree.begin();
        path.push_back(vertex);
        zeroIndegree.erase(zeroIndegree.begin());
        for (auto e : graph[vertex]){
            if (--indegree[e] == 0){
                zeroIndegree.insert(e);
            }
        }
    }
    for (auto e : path){
        cout << e << endl;
    }
    return  0;
}

shiyang6017
164 声望60 粉丝