toposort Algorithm

The toposort algorithm, or topological sorting algorithm, is a linear ordering algorithm used for directed acyclic graphs (DAGs). It produces a linear ordering of the vertices in such a way that for every directed edge (u, v) from vertex u to vertex v, u comes before v in the ordering. Topological sorting has various applications in scheduling, determining the sequence of tasks with dependencies, or finding a valid sequence of courses to take in a curriculum with prerequisites. The algorithm works by repeatedly selecting a vertex with no incoming edges, removing it from the graph along with its outgoing edges, and adding it to the linear order. This process is repeated until all vertices have been processed. There are several ways to implement the toposort algorithm: one common method is the depth-first search (DFS) based algorithm, where vertices are visited in depth-first order, and another is the Kahn's algorithm, which iteratively removes vertices with no incoming edges. In both cases, if the graph contains cycles, then a valid topological ordering is not possible, and the algorithm will not provide a correct result.
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[10001];
priority_queue<int,vector<int>,greater<int> >q;
queue<int>a;
bool visited[10001];
int indegree[10001];
int main()
{
	int n,m,u,v;
	scanf("%d%d",&n,&m);
	while(m--)
	{
	    scanf("%d%d",&u,&v);
	    adj[u].push_back(v);
	    indegree[v]++;
	}
	for(int i=1;i<=n;i++)
	    if(!indegree[i])
	        q.push(i);
	int k=0;
	while(!q.empty())
	{
	    int u=q.top();
	    q.pop();
	    a.push(u);
	    for(auto it:adj[u])
	    {
	        indegree[it]--;
	        if(!indegree[it])
	            q.push(it);
	    }
	    ++k;
	}
	if(k!=n)
	    printf("Sandro fails.");
	else
	{
	    while(!a.empty())
	    {
	        printf("%d ",a.front());
	        a.pop();
	    }
	}
}

LANGUAGE:

DARK MODE: