https://en.wikipedia.org/wiki/Topological_sorting
1 struct pointtype
2 {
3 vector<int> next;
4 int in;
5 }point[1000001];
6 int n,m;
7 queue<int> q;
8 list<int> res;
9 void init()
10 {
11 scanf("%d%d",&n,&m);
12 for(int i=1;i<=n;i++)
13 {
14 point[i].in=0;
15 point[i].next.clear();
16 }
17 for(int i=1;i<=m;i++)
18 {
19 int x,y;
20 scanf("%d%d",&x,&y);
21 point[x].next.push_back(y);
22 point[y].in+=1;
23 }
24 for(int i=1;i<=n;i++)
25 {
26 if(point[i].in==0)
27 {
28 q.push(i);
29 }
30 }
31 return;
32 }
33 bool topological_sorting()//是否存在拓扑序及其解
34 {
35 while(!q.empty())
36 {
37 int now=q.front();
38 q.pop();
39 res.push_back(now);
40 vector<int>::iterator it;
41 for(it=point[now].next.begin();it!=point[now].next.end();it++)
42 {
43 point[*it].in-=1;
44 if(point[*it].in==0)
45 {
46 q.push(*it);
47 }
48 }
49 point[now].next.clear();
50 }
51 bool flag=true;
52 for(int i=1;i<=n;i++)
53 {
54 if(!point[i].next.empty())
55 {
56 flag=false;
57 break;
58 }
59 }
60 return flag;
61 }