码迷,mamicode.com
首页 > 其他好文 > 详细

topsort

时间:2014-07-22 22:44:52      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   re   

#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

标签:style   blog   color   io   for   re   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!