<span style="font-size:18px;"># include <cstdio> # include <vector> # include <queue> # include <cstring> # include <iostream> # include <algorithm> using namespace std; const int maxn = 500 + 5; vector <int> g[maxn]; int n,m,du[maxn],l[maxn]; void topsort(){ int tot = 0; priority_queue <int> q; //使用优先队列,默认重大到小;所以存负数; for(int i = 1;i <= n;i++) if(!du[i]) q.push(-i); //将入度为0的点放入队列; while(!q.empty()){ int x = -q.top();q.pop(); l[tot++] = x; for(int j = 0;j < g[x].size();j++){ int t = g[x][j]; du[t] --; if(!du[t]) q.push(-t); } } } int main() { //freopen("a.txt","r",stdin); while(~scanf("%d%d",&n,&m)){ memset(du,0,sizeof(du)); memset(l,0,sizeof(l)); //vector数组清零; for(int i = 1;i <= n;i++) g[i].clear(); vector <int>::iterator it; for(int i = 0;i < m;i++){ int x,y; scanf("%d%d",&x,&y); //避免重复边计数; it = find(g[x].begin(),g[x].end(),y); if(it == g[x].end()){ g[x].push_back(y); du[y] ++; } } // for(int i = 1;i <= n;i++){ // for(int j = 0;j <g[i].size();j++) printf("%d ",g[i][j]); // printf("\n"); // } //进行拓扑排序; topsort(); for(int i = 0;i < n - 1;i++) printf("%d ",l[i]); printf("%d\n",l[n-1]); } }</span>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-09 08:06:49