1. 程式人生 > >HDU 2647 Reward(拓撲排序)

HDU 2647 Reward(拓撲排序)

empty case acm size col .cn ble ger dem

題目鏈接: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(拓撲排序)