题意:给出多个任务,以及一系列任务的关系表示某个任务必须在某个任务前完成,问一个合理的任务完成顺序
拓扑序的裸题,一开始用大白书的写法,后来发现并不好用,就换了BFS又A了一遍。
原:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h>
2 #include<string.h>
3 #include<algorithm>
4 using namespace std;
5 const int maxm=105;
6
7 int vis[maxm],topo[maxm],t;
8 int head[maxm],point[maxm*maxm],nxt[maxm*maxm],size;
9
10 void add(int a,int b){
11 point[size]=b;
12 nxt[size]=head[a];
13 head[a]=size++;
14 }
15
16 bool dfs(int s){
17 vis[s]=-1;
18 for(int i=head[s];~i;i=nxt[i]){
19 int j=point[i];
20 if(vis[j]==-1)return 0;
21 if(!vis[j]&&!dfs(j))return 0;
22 }
23 vis[s]=1;
24 topo[t--]=s;
25 return 1;
26 }
27
28 bool toposort(int n){
29 t=n;
30 memset(vis,0,sizeof(vis));
31 for(int i=1;i<=n;++i){
32 if(!vis[i]){
33 if(!dfs(i))return 0;
34 }
35 }
36 return 1;
37 }
38
39 int main(){
40 int n,m;
41 while(scanf("%d%d",&n,&m)!=EOF&&n+m){
42 memset(head,-1,sizeof(head));
43 size=0;
44 for(int i=1;i<=m;++i){
45 int a,b;
46 scanf("%d%d",&a,&b);
47 add(a,b);
48 }
49 toposort(n);
50 for(int i=1;i<=n;++i){
51 printf("%d",topo[i]);
52 if(i==n)printf("\n");
53 else printf(" ");
54 }
55 }
56 return 0;
57 }
BFS:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h>
2 #include<string.h>
3 #include<queue>
4 using namespace std;
5
6 int ma[105][105],id[105],n;
7
8 void init(){
9 memset(ma,0,sizeof(ma));
10 memset(id,0,sizeof(id));
11 }
12
13 void topo(){
14 queue<int>q;
15 for(int i=1;i<=n;++i)if(!id[i])q.push(i);
16 int cnt=0;
17 while(!q.empty()){
18 int u=q.front();
19 q.pop();
20 printf("%d",u);
21 if(++cnt==n)printf("\n");
22 else printf(" ");
23 for(int i=1;i<=n;++i)if(ma[u][i]){
24 id[i]--;
25 if(!id[i])q.push(i);
26 }
27 }
28 }
29
30 int main(){
31 int m;
32 while(scanf("%d%d",&n,&m)!=EOF&&n+m){
33 init();
34 while(m--){
35 int a,b;
36 scanf("%d%d",&a,&b);
37 if(!ma[a][b]){
38 ma[a][b]=1;
39 id[b]++;
40 }
41 }
42 topo();
43 }
44 return 0;
45 }