zoukankan      html  css  js  c++  java
  • topsort

    #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?'
    ':' ');
        }
    }
  • 相关阅读:
    缓存
    java垃圾回收机制GC(Garbage Collection)
    设计模式之适配器模式
    数据的水平分片意义
    屏幕坏点简单检查方法(网页纯色检查)
    Mac OS X上如何实现到Linux主机的ssh免登陆[forward]
    25个必须记住的SSH命令[forward]
    资料链接整理
    JAVA学习网站收集
    详细介绍ORACLE sqlplus命令(转)
  • 原文地址:https://www.cnblogs.com/llei1573/p/3859909.html
Copyright © 2011-2022 走看看