#include <stdio.h> #include <string.h> #include <queue> using namespace std; #define N 505 int ma[N][N],ans[N],indegree[N]; int main() { int i,j,n,m; while(~scanf("%d %d",&n,&m)) { memset(ma,0,sizeof(ma)); memset(indegree,0,sizeof(indegree)); while(m--) { int x,y; scanf("%d %d",&x,&y); if(!ma[x][y]) indegree[y]++; ma[x][y] = 1; } queue<int>q; int k = 0; for(i = 1; i <= n ; i++) if(indegree[i] == 0) {indegree[i]--;q.push(i);break;} while(!q.empty()) { int cur = q.front(); q.pop(); ans[k++] = cur; for(i = 1 ; i <= n ; i++) { if(ma[cur][i]) { ma[cur][i] = 0; indegree[i]--; } } for(j = 1 ; j <= n ; j++) if(indegree[j] == 0) {indegree[j]--;q.push(j);break;} } for(i = 0 ; i <k ; i++) printf("%d%c",ans[i],i == k-1?' ':' '); } }
#include <stdio.h> #include <string.h> #include <queue> #include <vector> using namespace std; #define N 505 int ans[N],indegree[N]; int main() { int i,j,n,m; vector<int>e[N]; while(~scanf("%d %d",&n,&m)) { memset(e,0,sizeof(e)); memset(indegree,0,sizeof(indegree)); while(m--) { int x,y; scanf("%d %d",&x,&y); e[x].push_back(y); indegree[y]++; } queue<int>q; int k = 0; for(i = 1; i <= n ; i++) if(indegree[i] == 0) {indegree[i]--;q.push(i);break;} while(!q.empty()) { int cur = q.front(); q.pop(); ans[k++] = cur; for(i = 0 ; i < e[cur].size() ; i++) indegree[e[cur][i]]--; for(j = 1 ; j <= n ; j++) if(indegree[j] == 0) {indegree[j]--;q.push(j);break;} } for(i = 0 ; i <k ; i++) printf("%d%c",ans[i],i == k-1?' ':' '); } }