https://www.cnblogs.com/1242118789lr/p/6740930.html
可以用邻接表也可以用邻接矩阵
当数据量级很大的时候我们选择邻接表,数据量小的时候可以选择邻接表也可以选择邻接矩阵
如UVA10305
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 <= n <= 100 and m . n is the number of tasks (numbered from 1 to n ) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j , representing the fact that task i must be executed before task j . An instance with n = m = 0 will finish the input.
Output
For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3
第一种:,邻接表(vector存图)
#include<iostream> #include<queue> #include<cstring> #include<vector> using namespace std; const int N= 1e4+7; vector<int>ve[N]; int in[N]; int main(){ int n,m; while(cin>>n>>m){ if(n==0&&m==0) break; queue<int>que; memset(in,0,sizeof(in)); int x,y; for(int i=1;i<=m;i++){ scanf("%d%d",&x,&y); in[y]++; ve[x].push_back(y);//保存的是x可以到达y } for(int i=1;i<=n;i++){ if(in[i]==0){ que.push(i); } } int n1=n; while(que.size()){ int y=que.front(); que.pop(); n1--; if(n1==0) printf("%d\n",y); else printf("%d ",y); for(int i=0;i<ve[y].size();i++){ in[ve[y][i]]--; if(in[ve[y][i]]==0){ que.push(ve[y][i]); } } } for(int i=1;i<=n;i++){ ve[i].clear(); } } return 0; }
拓扑排序的另外一个重要的用法就是用来判断图中是否存在一个环,如果说图中存在环的话,那么环内部的点不会出现度数为0的点。也就是说当队列为空的时候,环中的点不会被遍历到,所以我们可以通过统计我们遍历到点的数目,如果等于总的数目,说明每个点都遍历到了,不存在环,否则的话,一定存在环。