首页 > 代码库 > 拓扑排序
拓扑排序
#include <stdio.h>#include <string.h>#include <queue>using namespace std;#define N 505int 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?‘\n‘:‘ ‘); }}
#include <stdio.h>#include <string.h>#include <queue>#include <vector>using namespace std;#define N 505int 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?‘\n‘:‘ ‘); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。