HDU 2647 Reward(拓扑排序)

Posted leonard-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 2647 Reward(拓扑排序)相关的知识,希望对你有一定的参考价值。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2647

题目:

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
 
题解:题目中有分层,用一个cost数组存一下每个点的花费,注意更新花费的时候是以最大值,因为可能这个在当前层的花费+1还没有其他层花费高,但是要满足所有层,就需要最大花费。
 1 #include <queue>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 const int N=1e4+10;
 8 int cost[N],in[N];
 9 vector <int> E[N];
10 int n,m;
11 
12 bool toposort(){
13     int cnt=0;
14     queue <int> Q;
15     for(int i=1;i<=n;i++) if(!in[i]) Q.push(i);
16     while(!Q.empty()){
17         int u=Q.front();Q.pop();
18         cnt++;
19         for(int i=0;i<E[u].size();i++){
20             int v=E[u][i];
21             in[v]--;
22             cost[v]=max(cost[v],cost[u]+1);
23             if(in[v]==0) Q.push(v);
24         }
25     }
26     if(cnt==n) return true;
27     else return false;
28 }
29 
30 int main(){
31     int a,b;
32     while(scanf("%d %d",&n,&m)!=EOF){
33         for(int i=0;i<N;i++) E[i].clear();
34         memset(in,0,sizeof(in));
35         memset(cost,0,sizeof(cost));
36         for(int i=1;i<=m;i++){
37             scanf("%d %d",&a,&b);
38             E[b].push_back(a);
39             in[a]++;
40         }
41         if(!toposort()) printf("-1\n");
42         else{
43             int sum=0;
44             for(int i=1;i<=n;i++) sum+=cost[i];
45             printf("%d\n",sum+888*n);
46         }
47     }
48     return 0;
49 }

 

以上是关于HDU 2647 Reward(拓扑排序)的主要内容,如果未能解决你的问题,请参考以下文章

hdu 2647 Reward - 拓扑排序

HDU2647Reward(拓扑排序)

hdu 2647 Reward(拓扑排序+反图)

HDOJ 2647 Reward 逆拓扑排序+分层

hdu2647(拓扑排序)

Reward HDU - 2647