题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2647
题目:
- Problem Description
- Dandelions 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 as reward should more than bs.Dandelions unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every works reward will be at least 888 , because its 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 as reward should be more than bs.
- Output
- For every case ,print the least money dandelion s uncle needs to distribute .If its 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 还没有其他层花费高, 但是要满足所有层, 就需要最大花费
- #include <queue>
- #include <cstdio>
- #include <vector>
- #include <cstring>
- using namespace std;
- const int N=1e4+10;
- int cost[N],in[N];
- vector <int> E[N];
- int n,m;
- bool toposort(){
- int cnt=0;
- queue <int> Q;
- for(int i=1;i<=n;i++) if(!in[i]) Q.push(i);
- while(!Q.empty()){
- int u=Q.front();Q.pop();
- cnt++;
- for(int i=0;i<E[u].size();i++){
- int v=E[u][i];
- in[v]--;
- cost[v]=max(cost[v],cost[u]+1);
- if(in[v]==0) Q.push(v);
- }
- }
- if(cnt==n) return true;
- else return false;
- }
- int main(){
- int a,b;
- while(scanf("%d %d",&n,&m)!=EOF){
- for(int i=0;i<N;i++) E[i].clear();
- memset(in,0,sizeof(in));
- memset(cost,0,sizeof(cost));
- for(int i=1;i<=m;i++){
- scanf("%d %d",&a,&b);
- E[b].push_back(a);
- in[a]++;
- }
- if(!toposort()) printf("-1\n");
- else{
- int sum=0;
- for(int i=1;i<=n;i++) sum+=cost[i];
- printf("%d\n",sum+888*n);
- }
- }
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2502955.html