简单的拓扑排序,每次都找到入度为0的节点输出,这个节点出发的连到的节点入度都减1。第一次写拓扑排序,还需改进。
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> using namespace std; int rudu[505]; vector<int>abc[505]; int main() { int n, m, i, x, y, j, k; while (~scanf("%d%d", &n, &m)) { memset(rudu, 0, sizeof(rudu)); for (i = 0; i < 504; i++) abc[i].clear(); for (i = 0; i < m; i++) { scanf("%d%d", &x, &y); rudu[y]++; abc[x].push_back(y); } for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (rudu[j] == 0) { if (i < n) printf("%d ", j); else printf("%d ", j); rudu[j]--; for (k = 0; k < abc[j].size(); k++) rudu[abc[j][k]]--; break; } } } } return 0; }