program TopSort; var map,link:array [1..100,1..100] of integer; v,pnt:array [1..100] of integer; n,m,a,b,i,j,k:integer; begin fillchar(map,sizeof(map),0); fillchar(link,sizeof(link),0); fillchar(v,sizeof(v),0); readln(n,m); for i:=1 to m do begin readln(a,b); map[a,b]:=1; v[b]:=v[b]+1; end; i:=0; link:=map; while (i<n) do begin j:=1; while (v[j]<>0) do inc(j); v[j]:=-1; for k:=1 to n do if link[j,k]=1 then begin dec(v[k]);link[j,k]:=0; end; inc(i); pnt[i]:=j; end; for i:=1 to n do writeln(pnt[i]); end.
拓扑序列 C++核心代码
bool TopologicalSort(int a[][101]) //可以完成拓扑排序则返回True { int n = a[0][0], i, j; int into[101], ans[101]; memset(into, 0, sizeof(into)); memset(ans, 0, sizeof(ans)); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (a[i][j] > 0) into[j]++; } } into[0] = 1; for (i = 1; i <= n; i++) { j = 0; while (into[j] != 0) { j++; if (j > n) return false; } ans[i] = j; into[j] = -1; for (int k = 1; k <= n; k++) { if (a[j][k] > 0) into[k]--; } } for (i = 1; i <= n; i++) { cout << ans[i] << " "; } cout << endl; return true; }