The dfs algorithm times out in this particular question. With some clever tricks you can get the complexity of the solution to O(m). You need to eliminate the sort that you are using to sort all the edges in order. I maintained a list of reverse edges, i.e for two edges u->v and w->v, I initially added them in the list li[v]->u->w. and then traversing from 1 to n, I created the corrected directed edges, but this time they come out to be automatically in order.
Anyway this times out(on test case12 for me). You need a very optimized algorithm for this. The algorithm templatetypedef mentions works fine, probably the recursion overhead in dfs is a bit too much in the dfs algorithm.
The idea is really simple, you can read about this here http://en.wikipedia.org/wiki/Topological_sorting
Basically, you can complete the tasks with zero indegree and once the task is completed, you remove all the outgoing edges and update all the indegrees and find another task with zero indegree. To get things in order, you can use a 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;
}