diff --git a/Kahn's algo(Toposort in DAG).cpp b/Kahn's algo(Toposort in DAG).cpp new file mode 100644 index 0000000..4c90235 --- /dev/null +++ b/Kahn's algo(Toposort in DAG).cpp @@ -0,0 +1,72 @@ +#include +using namespace std; +#define ll long long +#define ld long double +#define pb push_back +#define pf push_front +#define mp make_pair +#define F first +#define S second +#define mod 1000000007 +#define INF INT_MAX +#define vl vector +#define vi vector +#define pi pair +#define pl pair +#define vpl vector +#define vpi vector +#define ml map +#define mi map +#define m(a,b) map +#define YesNo(f) if(f){cout<<"YES"< q; + for(int i=1;i<=n;i++){ + if(in[i]==0){ + q.push(i); + } + } + while(!q.empty()){ + int node=q.front(); + q.pop(); + sorted.pb(node); + for(auto i: adj[node]){ + in[i]--; + if(in[i]==0){ + q.push(i); + } + } + } + // checking if the sort is valid, i.e. if the graph contains cycle + // all the nodes will not be present in the final sort + return sorted.size()==n; +} + +int main() +{ + fastIO; +// freopen("input.txt","r",stdin); +// freopen("output.txt","w",stdout); + int t=1; + // cin>>t; + while(t--){ + int n,m,x,y; + cin>>n>>m; + for(int j=0;j>x>>y; + adj[x].pb(y); + in[y]++; + } + } + +return 0; +} \ No newline at end of file