1. 程式人生 > >拓撲排序簡單應用poj2367

拓撲排序簡單應用poj2367

//題目大意:輸入n,接下來n行,每一行的編號都比這一行的數字優先
//關於拓撲排序的內容可以看本部落格http://blog.csdn.net/fengsigaoju/article/details/47185297
 #include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
queue<int>q;
 int main()
 {
     int n,m,i,j;
     int a[105][105];
     int indegree[105];
     int ans[105],count,temp;
     scanf("%d",&n);
     memset(a,0,sizeof(a));
     memset(indegree,0,sizeof(indegree));
     memset(ans,0,sizeof(ans));
     count=1;
     for (i=1;i<=n;i++)
        while(scanf("%d",&m)==1&&m)
     {
         a[i][m]=1;
         indegree[m]++;
     }
   for (i=1;i<=n;i++)
        if (!indegree[i])
        {
        q.push(i);
        ans[count++]=i;
        }
      while(!q.empty())
      {
          temp=q.front();
          q.pop();
          for (i=1;i<=n;i++)
          {
            if (a[temp][i])
            {
            indegree[i]--;
             if (!indegree[i])
             {
                q.push(i);
                ans[count++]=i;
             }
            }
          }
      }
      for (i=1;i<=n-1;i++)
        printf("%d ",ans[i]);
        printf("%d\n",ans[n]);
        return 0;

 }