hdu 1285

第一个图论题,拓扑排序;

挺容易的,基本上就是一个裸地拓扑排序;

代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 int a[505][505],ans[505],cnt[505],n,m,x,y;
 5 
 6 void top_sort()
 7 {
 8     for(int i=1; i<=n; i++)
 9         for(int j=1; j<=n; j++)
10             if(a[i][j]==1)
11                 cnt[j]++;
12     for(int i=1; i<=n; i++)
13     {
14         int k=1;
15         while(cnt[k]!=0) k++;
16         ans[i]=k;
17         cnt[k]--;
18         for(int j=1; j<=n; j++)
19             if(a[k][j])
20                 cnt[j]--;
21     }
22 }
23 
24 int main()
25 {
26     while(scanf("%d%d",&n,&m)!=EOF)
27     {
28         memset(cnt,0,sizeof cnt);
29         memset(a,0,sizeof a);
30         memset(ans,0,sizeof ans);
31         for(int i=0; i<m; i++)
32         {
33             scanf("%d%d",&x,&y);
34             a[x][y]=1;
35         }
36         top_sort();
37         for(int i=1; i<n; i++)
38             printf("%d ",ans[i]);
39         printf("%d
",ans[n]);
40     }
41     return 0;
42 }
View Code
原文地址:https://www.cnblogs.com/yours1103/p/3293318.html