Problem from the textbook.
You are given a list of projects and a list of dependencies(which is a list of pairs of projects, where the second project is dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, return a error.
Example:
Input
Projects: a, b, c, d, e, f
dependencies:(a, d), (f, b), (b, d), (f, a), (d, c)
output: f, e, a, b, d, c
A straight forward algorthm by topological sort. But it is not very efficient.
#include <algorithm>
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <list>
using namespace std;
vector<char> buildOrder(const vector<char> &projects,
const vector<pair<char, char>> &dependencies)
{
unordered_map<char, int> table;
queue<char> processNext, order;
vector<char> result;
// build the dependenciesTree
list<pair<char, char>> tree;
// create the table.
for(auto &x : projects)
table[x] = 0;
// count inbound for each node:
for (auto &item : dependencies)
{
++table[item.second];
tree.push_back(item);
}
for (auto &x : table)
{
if (x.second == 0)
processNext.push(x.first);
}
while (!processNext.empty())
{
auto &x = processNext.front();
// iterator all about x to modify the inbound.
for (auto iter = tree.begin(); iter != tree.end();)
{
// if it is the edge of the node x.
if (iter->first == x)
{
table[iter->second]--;
// add the 0 inbound node to processNext
if(table[iter->second] == 0)
processNext.push(iter->second);
iter = tree.erase(iter);
}
else
{
++iter;
}
}
// update to inbound and add to ProcessNext();
order.push(x);
processNext.pop();
}
// we build the order correctly.
if(order.size() == projects.size()) {
while(!order.empty()) {
result.push_back(order.front());
order.pop();
}
}
return result;
}
int main()
{
vector<char> projects = {'a', 'b', 'c', 'd', 'e', 'f'};
vector<pair<char, char>> dependencies = {
make_pair('a', 'd'), make_pair('f', 'b'), make_pair('b', 'd'), make_pair('f', 'a'),
make_pair('d', 'c')};
auto x = buildOrder(projects, dependencies);
for(auto & a : x)
cout << a << " ";
cout << endl;
return 0;
}
output:
the time complexity is O(N+N*D) where N is the number of the projects, and the D is the number of the dependencies.
Now try to improve this algorithm by graph structure and topological sort algorithm.