首页 > 代码库 > HDU2647 Reward 【拓扑排序】
HDU2647 Reward 【拓扑排序】
Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4379 Accepted Submission(s): 1335
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
题目大意:老板要发酬劳,但是工人酬劳不一样,有N个人,M种情况。a的酬劳一定
要高于b。每个人最低酬劳为888,问:老板最少要花费多少钱。
思路:以b->a为有向边建立拓扑排序,不满足排序就输出"-1",否则就进行拓扑排序,
将拓扑排序的点看成一层一层的,无入度的为第一层,通过一条边能走到的为第二层。
通过两条边才能走到的为第三层。每一层都比前一层多一块钱。最后输出总钱数。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 10010; const int MAXM = 20010; int head[MAXN],N,M,ans,indegree[MAXN],queue[MAXN],money[MAXN]; struct EdgesNode { int to; int w; int next; }; EdgesNode Edges[MAXM]; int toposort() { int iq = 0; for(int i = 1; i <= N; i++) { if(indegree[i]==0) queue[iq++] = i; } for(int i = 0; i < iq; i++) { ans += money[queue[i]]; for(int k = head[queue[i]]; k != -1; k = Edges[k].next) { indegree[Edges[k].to]--; if(indegree[Edges[k].to] == 0) { money[Edges[k].to] = money[queue[i]] + 1; //money[Edges[k].to] = money[k] + 1;是错的。 queue[iq++] = Edges[k].to; } } } if(iq == N) return ans; else return 0; } int main() { int x,y; while(cin >> N >> M) { memset(head,-1,sizeof(head)); memset(Edges,0,sizeof(Edges)); memset(indegree,0,sizeof(indegree)); memset(queue,0,sizeof(queue)); memset(money,0,sizeof(money)); for(int i = 0; i < M; i++) { cin >> x >> y; Edges[i].to = x; Edges[i].w = 1; Edges[i].next = head[y]; head[y] = i; indegree[x]++; } ans = N*888; if(!toposort()) cout << "-1" << endl; else cout << ans << endl; } return 0; }
HDU2647 Reward 【拓扑排序】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。