首页 > 其他 > 详细

topsort

时间:2014-07-22 22:44:42      阅读:311      评论:0      收藏:0      [点我收藏+]
#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?\n: );
    }
}
#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?\n: );
    }
}

topsort,布布扣,bubuko.com

topsort

原文:http://www.cnblogs.com/llei1573/p/3859909.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!