hdu 2647 Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9814    Accepted Submission(s): 3134


Problem Description
Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
 

 

Input
One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
 

 

Output
For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.
 

 

Sample Input
21
1 2
2 2
1 2
2 1
 

 

Sample Output
1777
-1
 

 

Author
dandelion
 

 

Source
 .
拓扑排序求第几层
有环或者无法遍历它
则无解
#include <cstring>
#include <cstdio>
#include <queue>
#define N 20005
using namespace std;
struct Edge{
    int next,to;
}edge[N];
queue<int>q;
int ans,head[N],cen[N],cnt,n,m,rd[N];
inline void ins(int u,int v)
{
    edge[++cnt].next=head[u];
    edge[cnt].to=v;
    head[u]=cnt;
}
int main()
{
    for(;scanf("%d%d",&n,&m)!=EOF;)
    {
        memset(rd,0,sizeof(rd));
        memset(cen,0,sizeof(cen));
        memset(edge,0,sizeof(edge));
        memset(head,0,sizeof(head));
        ans=0;cnt=0;
        bool flag=0; 
        for(int x,y;m--;)
        {
            scanf("%d%d",&x,&y);
            ins(y,x);
            rd[x]++;
        }
        for(int i=1;i<=n;++i) if(!rd[i]) q.push(i),cen[i]=1;
        if(!q.size()) {printf("-1\n");continue;} 
        for(int now;!q.empty();)
        {
            now=q.front();q.pop();
            for(int u=head[now];u;u=edge[u].next)
            {
                int v=edge[u].to;
                if(rd[v])
                {
                    rd[v]--;
                    if(!rd[v])
                    {
                        cen[v]=cen[now]+1;
                        q.push(v); 
                    }
                }
            }
        }
        for(int i=1;i<=n;++i)
        {
            if(!cen[i]) {printf("-1\n");flag=1;break;}
            ans+=(cen[i]+888-1);
        }
        if(!flag) printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2017-08-24 09:54  杀猪状元  阅读(188)  评论(0编辑  收藏  举报