[itint5]任务调度

http://www.itint5.com/oj/#10

拓扑排序。首先按照题目给出的数据结构复杂度不会是O(v+e)的,所以先要变换数据结构。二来写的时候用一个stack会更好点。还有就是题目里其实ID就是1到n。

#include <map>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
typedef int JobID;

/*
 * deps[id]表示任务id所依赖的任务
 * 如果存在合法的任务完成序列,返回true,否则返回false
 * 合法的任务序列请存放在参数result中(已经分配空间,不需要push_back)
 */
 /*
    id are from 1 to n
 */
bool jobSchedule(const map<JobID, vector<JobID> > &deps, int n,
                                   vector<JobID> &result) {
    map<JobID, vector<JobID>> rmap;
    vector<int> indeg(n+1, 0);
    for (map<JobID, vector<JobID> >::const_iterator it = deps.begin(); it != deps.end(); it++) {
        indeg[it->first] = it->second.size();
        for (int i = 0; i < it->second.size(); i++) {
            rmap[it->second[i]].push_back(it->first);
        }
    }
    stack<JobID> stak;
    for (int i = 1; i <= n; i++) {
        if (indeg[i] == 0) {
            stak.push(i);
        }
    }
    for (int i = 0; i < n; i++) {
        if (stak.empty()) return false;
        JobID id = stak.top();
        stak.pop();
        result[i] = id;
        for (int j = 0; j < rmap[id].size(); j++) {
            indeg[rmap[id][j]]--;
            if (indeg[rmap[id][j]] == 0) {
                stak.push(rmap[id][j]);
            }
        }
    }
    return true;
}

java的代码参见:http://www.itint5.com/discuss/8/%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6java%E7%A8%8B%E5%BA%8F

原文地址:https://www.cnblogs.com/lautsie/p/3524986.html