The dfs algorithm is played out in this particular question. With some clever tricks, you can get the complexity of solving O (m). You need to eliminate the sorting you use to sort all the edges in order. I saved a list of back edges, i.e. For two edges u-> v and w-> v, I initially added them to the list li [v] β u-> w. and then, going from 1 to n, I created fixed directed edges, but this time they come out automatically in order.
In any case, this is the time (in test case 12 for me). For this you need a very optimized algorithm. The templatetypedef algorithm mentions that it works fine, perhaps the recursion overhead in dfs is too much in the dfs algorithm.
The idea is very simple, you can read about it here http://en.wikipedia.org/wiki/Topological_sorting
In principle, you can perform tasks with a zero index, and after the task is completed, you delete all outgoing edges and update all indexes and find another task with a zero index. To keep everything in order, you can use the priority queue.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int indeg [10005];
int topo [10005];
vector <int> g [10005];
int main () {
int n, m;
int cur = 0;
cin >> n >> m;
for (int i = 0; i <m; i ++) {
int x, y;
scanf ("% d% d", & x, & y);
indeg [y] ++;
g [x] .push_back (y);
}
priority_queue <int> q;
for (int i = 1; i <= n; i ++)
if (! indeg [i]) q.push (-1 * i);
while (! q.empty ()) {
int nd = -1 * q.top ();
q.pop ();
for (int i = 0; i <g [nd] .size (); i ++) {
indeg [g [nd] [i]] -;
if (! indeg [g [nd] [i]])
q.push (-1 * g [nd] [i]);
}
topo [cur ++] = nd;
}
if (cur! = n) {
cout << "Sandro fails." << endl;
return 0;
}
for (int i = 0; i <n-1; i ++)
printf ("% d", topo [i]);
printf ("% d \ n", topo [n-1]);
return 0;
}
source share