HDU 2647

思路:拓扑排序


#include<stdio.h>
  #include<string.h>
  typedef struct
  {
      int to;
      int next;
  }EdgeNode;
  EdgeNode Edge[20005];
  int head[10005],node[10005];
 int cnt,indegree[10005],vis[10005];
 void init()
 {
     cnt = 0;
     memset(vis,0,sizeof(vis));
     memset(head,-1,sizeof(head));
         memset(indegree,0,sizeof(indegree));
 }
 
 void add_edge(int n,int m)
 {
     Edge[cnt].to = n;
     Edge[cnt].next = head[m];
     head[m] = cnt++;
 }
 
 int main()
 {
     int n,m,a,b,i,j,k,t,p,sum;
     while(~scanf("%d%d",&n,&m))
     {
         init();
         sum = p = 0;
         while(m--)
         {
             scanf("%d%d",&a,&b);
             indegree[a]++;
             add_edge(a,b);
         }
         for(i = 0;i < n;i ++)
         {
             t = 0;
             for(j = 1;j <= n;j ++)
             {
                 if(indegree[j] == 0 && vis[j] == 0)
                     node[t++] = j;
             }
             sum += (888+p)*t;
             p++;
             for(j = 0;j < t;j ++)
             {
                 vis[node[j]] = 1;
                 for(k = head[node[j]];k != -1;k = Edge[k].next)
                 {
                     if(!vis[Edge[k].to])
                         indegree[Edge[k].to]--;
                 }
             }
         }
         for(i = 1;i <= n;i ++)
         {
             if(indegree[i])
             {
                 sum = -1;
                   break ;
             }
         }
         printf("%d\n",sum);
     }
     return 0;
 }


posted on 2014-04-30 18:35  ~Love()  阅读(86)  评论(0编辑  收藏  举报

导航