HDU 2647 - Reward(拓扑排序)

来源:互联网 发布:美工网 编辑:程序博客网 时间:2021/10/19 07:21

Reward

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


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
2 11 22 21 22 1
 

Sample Output
1777-1
 


===========================

注意边的方向


#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int MAXN=11111;const int MAXM=21111;const int INF=0x3f3f3f3f;int edge,n,m,a,b;int head[MAXN],ind[MAXN],que[MAXN],cost[MAXN];struct EdgeNode{    int to;    int next;}edges[MAXM];void addedge(int u,int v){    edges[edge].to=v;    edges[edge].next=head[u];    head[u]=edge++;}int main(){    while(~scanf("%d%d",&n,&m))    {        memset(head,-1,sizeof(head));        memset(ind,0,sizeof(ind));        edge=0;        int cnt=0,ans=0;        for(int i=1;i<=n;i++) cost[i]=888;        for(int i=0;i<m;i++)        {            scanf("%d%d",&a,&b);            addedge(b,a);            ind[a]++;        }        for(int i=1;i<=n;i++)        {            if(ind[i]==0)            {                que[cnt++]=i;                ans+=cost[i];            }        }        for(int i=0;i<cnt;i++)        {            for(int j=head[que[i]];j!=-1;j=edges[j].next)            {                ind[edges[j].to]--;                if(ind[edges[j].to]==0)                {                    que[cnt++]=edges[j].to;                    cost[edges[j].to]=cost[que[i]]+1 ;                    ans+=cost[edges[j].to];                }            }        }        if(cnt!=n) printf("-1\n");        else printf("%d\n",ans);    }    return 0;}