此题为数据结构基础图的训练参考
题目链接 http://acm.hust.edu.cn/vjudge/problem/19494
解题思路
拓扑排序。
一开始在想如果排序不唯一oj能判断出来吗?结果oj能判断。。。
可以仿照白书里dfs的做法,也可以采用邻接表存储,入度判断的方法。
代码采用的是后一种。
注意 可能有任务为0的情况
代码
#include<iostream> #include<cstdio> //#define LOCAL using namespace std; const int maxLen = 101; struct ArcNode { int task; int adjvex; ArcNode *next; }; struct VertexNode { int task; int in; ArcNode *firstEdge; }v[maxLen]; int q[2*maxLen]; int n, m; void TopSort() { int top = -1; int count = 0; for(int i=0; i<n; i++) if(v[i].in == 0) q[++top] = i; while(top != -1) { int j=q[top--]; count++; if(count != n) cout << v[j].task << ' '; else cout << v[j].task; ArcNode *p = v[j].firstEdge; while(p != NULL) { int k = p->adjvex; v[k].in--; if(v[k].in == 0) q[++top] = k; p = p->next; } } } int main() { #ifdef LOCAL freopen("data.txt", "r", stdin); freopen("ans.txt", "w", stdout); #endif cin >> n >> m; while(n!=0 && m!=0) { for(int i=0; i<n; i++) { v[i].in = 0; v[i].task = i+1; v[i].firstEdge = NULL; } for(int i=0; i<m; i++) { int x, y; cin >> x >> y; ArcNode *s = new ArcNode; s->task = y; s->adjvex = y-1; s->next = v[x-1].firstEdge; v[x-1].firstEdge = s; v[y-1].in++; } if(n!=0)TopSort(); cout << endl; cin >> n >> m; } return 0; }