HDU 5965 Gym Class 贪心+toposort

分析:就是给一些拓补关系,然后求最大分数,所以贪心,大的越靠前越好,小的越靠后越好

剩下的就是toposort,当然由于贪心,所以使用优先队列

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <utility>
using namespace std;
typedef long long LL;
const int N=1e5+5;
const int INF=0x3f3f3f3f;
const LL mod=1e9+7;
priority_queue<int>q;
struct Edge{
    int v,next;
}edge[N];
int head[N],tot;
void add(int u,int v){
   edge[tot].v=v;
   edge[tot].next=head[u];
   head[u]=tot++; 
}
int d[N];
int main()
{
    int T,cas=0;
    scanf("%d",&T);
    while(T--){
      // printf("Case #%d:\n",++cas);
      int n,m;
      scanf("%d%d",&n,&m);
      memset(head,-1,sizeof(head)),tot=0;
      memset(d,0,sizeof(d));
      for(int i=1;i<=m;i++){
         int u,v;
         scanf("%d%d",&u,&v);
         add(u,v);++d[v];
      }
      while(!q.empty())q.pop();
      for(int i=1;i<=n;++i)
      if(!d[i])q.push(i);
      LL ans=0;int cur=-1;
      while(!q.empty()){
         int u=q.top();
         q.pop();
         if(cur==-1)cur=u;
         else cur=min(cur,u);
         ans+=cur;
         for(int i=head[u];~i;i=edge[i].next){
           int v=edge[i].v;
           --d[v];
           if(!d[v])q.push(v);
         } 
      }
      printf("%I64d\n",ans); 
    }
    return 0;
}
View Code

 

posted @ 2016-05-23 22:34  shuguangzw  阅读(160)  评论(0编辑  收藏  举报