拓扑排序 | #任务调度#

任务调度

https://www.nowcoder.com/practice/88d5fa34fe0748e09062e48c6ae6ffc7

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;

int main() {
    int n;
    map<string, int> degree;//入度
    map<string, vector<string>> grid;//邻接矩阵
    set<string> nodes;
    while (cin >> n) { // 注意 while 处理多个 case
        string task;
        for (int i = 0; i < n; i++) {
            cin>>task;
            int index=task.find('(');
            string s1=task.substr(0,index);
            nodes.insert(s1);
            string tmp="";
            for(int j=index+1;j<task.size();j++){
                if((task[j]==','||task[j]==')')&&tmp.compare("NULL")!=0){
                    // arr.push_back(tmp);
                    grid[s1].push_back(tmp);
                    degree[tmp]++;//入度增加
                    nodes.insert(tmp);
                    tmp="";
                }else
                    tmp+=task[j];
            } 
        }
        queue<string> q;
        for(string s:nodes){
            if(degree[s]==0)
                q.push(s);      
        }
        vector<string> ans;
        while(!q.empty()){
            int size=q.size();
            for(int i=0;i<size;i++){
                string x=q.front();
                q.pop();
                ans.push_back(x);
                for(string neb:grid[x]){
                    degree[neb]--;
                    if(degree[neb]==0)
                        q.push(neb);
                }
            }
        }
        for_each(ans.begin(),ans.end(),[](string x){cout<<x<<" ";});
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务