HDU 2647 Reward

Reward

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

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 1 1 2 2 2 1 2 2 1
 
Sample Output
1777 -1
 
Author
dandelion
 
Source
 
Recommend
yifenfei   |   We have carefully selected several similar problems for you:  1811 2680 2112 2094 2544 
思路:拓扑排序+记录层数。
错因:因为有多组数据,数组和ans忘了清零。
 
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 20001
using namespace std;
queue<int>que;
int n,m,tot,num,ans,into[MAXN];
int to[MAXN],net[MAXN],head[MAXN],pre[MAXN];
void add(int u,int v){
    to[++tot]=v;net[tot]=head[u];head[u]=tot;
}
int main(){
    while(scanf("%d%d",&n,&m)!=EOF){
        num=0;tot=0;ans=0;
        memset(to,0,sizeof(to));
        memset(net,0,sizeof(net));
        memset(pre,-1,sizeof(pre));
        memset(into,0,sizeof(into));
        memset(head,0,sizeof(head));
        for(int i=1;i<=m;i++){
            int x,y;
            scanf("%d%d",&x,&y);
            add(y,x);
            into[x]++;
        }
        while(!que.empty())    que.pop();
        for(int i=1;i<=n;i++)
            if(!into[i]){
                num++;
                pre[i]=1;
                que.push(i);
            }
        while(!que.empty()){
            int now=que.front();
            que.pop();
            for(int i=head[now];i;i=net[i]){
                into[to[i]]--;
                if(!into[to[i]]){
                    num++;
                    pre[to[i]]=max(pre[now]+1,pre[to[i]]);
                    que.push(to[i]);
                }
            }
        }
        if(num!=n)    cout<<"-1"<<endl;
        else{
            for(int i=1;i<=n;i++)    ans+=888+(pre[i]-1);
            cout<<ans<<endl;
        }    
    }
}
细雨斜风作晓寒。淡烟疏柳媚晴滩。入淮清洛渐漫漫。 雪沫乳花浮午盏,蓼茸蒿笋试春盘。人间有味是清欢。
原文地址:https://www.cnblogs.com/cangT-Tlan/p/7502608.html