简单拓扑排序

  1 //hdu 1285
  2 
  3 #include<stdio.h>
  4 #include<string.h>
  5 #include<stack>
  6 using namespace std;
  7 int map[600][600],n,count[600],seq[600],ff;
  8 int topo()
  9 {
 10     int i,j;
 11     ff=0;
 12     while(ff<n)//当为排完
 13     {
 14         for(i=1;i<=n;i++)//从小开始找
 15         {
 16             if(count[i]==0)//入读为0
 17             {
 18                 count[i]--;
 19                 seq[ff++]=i;
 20                 for(j=1;j<=n;j++)//相关的点减度
 21                     if(map[i][j])
 22                     {
 23                         count[j]--;
 24                     }
 25 
 26                 break;
 27             }
 28         }
 29     }
 30     return 1;
 31 }
 32 int main()
 33 {
 34     int i,j,m;
 35     while(scanf("%d%d",&n,&m)!=EOF)
 36     {
 37         ff=0;
 38         memset(count,0,sizeof(count));
 39         memset(map,0,sizeof(map));
 40         for(i=0;i<m;i++)
 41         {
 42             int x,y;
 43             scanf("%d%d",&x,&y);
 44             if(map[x][y]==0)//重边
 45             {
 46                 map[x][y]=1;
 47                 count[y]++;//入读
 48             }
 49         }
 50         int ans=topo();
 51         if(ans)
 52         {
 53             for(i=0;i<ff;i++)
 54                 if(i==0)printf("%d",seq[i]);
 55                 else printf(" %d",seq[i]);
 56                 printf("\n");
 57         }
 58     }
 59 }
 60 
 61 
 62 
 63 
 64 /*模版
 65 #include<stdio.h>
 66 #include<string.h>
 67 int map[103][103],n,m;
 68 int c[103];
 69 int dfs(int u)
 70 {
 71     int i,j,l;
 72     c[u]=-1;
 73     for(i=0;i<n;i++)
 74         if(map[u][i])
 75         {
 76             if(c[i]<0)
 77                 return 0;
 78             else if(!c[i]&&!dfs(i))
 79                 return 0;
 80         }
 81     c[u]=1;
 82     return 1;
 83 }
 84 int topo()
 85 {
 86     int i,j;
 87     memset(c,0,sizeof(c));
 88     for(i=0;i<n;i++)
 89     {
 90         if(!c[i])
 91             if(!dfs(i))
 92                 return 0;
 93     }
 94     return 1;
 95 }
 96 int main()
 97 {
 98     int i,j,l;
 99     while(scanf("%d%d",&n,&m)!=EOF)
100     {    
101         memset(map,0,sizeof(map));
102         if(!n)
103             break;
104         for(i=0;i<m;i++)
105         {
106             int a,b;
107             scanf("%d%d",&a,&b);
108             map[a][b]=1;
109         }
110         if(!topo())
111             printf("NO\n");
112         else printf("YES\n");
113     }
114 }*/

 

posted @ 2015-05-11 22:17  sweat123  阅读(166)  评论(0编辑  收藏  举报