Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Note: topological sort result is not unique . so don't worried
- #include <iostream>
- #include <vector>
- #include <iterator>
- #include <queue>
- using namespace std;
- void topologicalsort(vector<int>v[],int n)
- {
- vector<int>indegree(n,0);
- vector<int>::iterator it;
- for(int i=0; i<n; i++)
- {
- for(it=v[i].begin(); it !=v[i].end(); it++)
- {
- indegree[*it]++;
- }
- }
- queue<int>q;
- vector<int>result;
- for(int i=0; i<n; i++)
- {
- if(indegree[i]==0)
- q.push(i);
- }
- int c=0;
- while(!q.empty())
- {
- int m=q.front();
- result.push_back(m);
- q.pop();
- for(it=v[m].begin(); it !=v[m].end(); it++)
- {
- --indegree[*it];
- if(indegree[*it]==0)
- {
- q.push(*it);
- }
- c++;
- }
- }
- if(c==n)
- {
- cout<< "Top sort: ";
- for(int i=0; i<result.size(); i++)
- cout<<result[i]<< " ";
- cout<<endl;
- }
- else
- {
- cout<< "The graph is not a DAG"<<endl;
- return ;
- }
- }
- int main()
- {
- int node,edge;
- cout<< "Number of the nodes and edges: ";
- cin>>node>>edge;
- vector<int>v[node];
- cout<< "Enter edge information(u,v)"<<endl;
- for(int i=0; i<edge; i++)
- {
- int m,n;
- cin>>m>>n;
- v[m].push_back(n);
- }
- topologicalsort(v,node);
- return 0;
- }
- /*
- 4 4
- 0 1
- 2 0
- 2 1
- 2 3
- 4 4
- 0 1
- 1 2
- 2 1
- 2 3
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement