HDU 2647 Reward 拓扑排序

来源:互联网 发布:淘宝客贷就是网商贷吗 编辑:程序博客网 时间:2024/06/15 14:16

Reward

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


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 11 22 21 22 1
 

Sample Output
1777

-1

题意:厂长想给员工发奖金,但是需要满足所有员工x奖金比员工y奖金对的要求,且奖金最少为888,现在给出员工人数和员工的要求,问最少需要分发多少奖金,如果无法满足所有的员工要求则输出-1.

思路:对所有员工进行拓扑排序,如果无法排序输出-1,否则对于排序后的员工我们从后往前模拟对奖金进行分配。

#include<stdio.h>#include<algorithm>#include<string.h>#include<vector>using namespace std;#define ll long longconst int maxm = 10005;vector<int>v[maxm];vector<int>p[maxm];int flag[maxm], a[maxm], L = 0, sum[maxm], b[maxm];void dfs(int k);int main(){int n, i, j, k, m, x, y, len;while (scanf("%d%d", &n, &m) != EOF){L = 0;memset(flag, 0, sizeof(flag));for (i = 0;i <= n;i++){v[i].clear();p[i].clear();}for (i = 1;i <= m;i++){scanf("%d%d", &x, &y);flag[y] ++;v[x].push_back(y);p[y].push_back(x);}len = 0;for (i = 1;i <= n;i++){if (flag[i] == 0)b[len++] = i;}for (i = 0;i < len;i++)dfs(b[i]);ll ans = 0;//printf("%d\n", L);if (L < n)printf("-1\n");else{memset(sum, 0, sizeof(sum));for (i = L - 1;i >= 0;i--){int xx = a[i];if (!sum[xx])sum[xx] = 888;for (j = 0;j < p[xx].size();j++)sum[p[xx][j]] = max(sum[p[xx][j]], sum[xx] + 1);}for (i = 1;i <= n;i++)ans += sum[i];printf("%lld\n", ans);}}return 0;}void dfs(int k){a[L++] = k;for (int j = 0;j < v[k].size();j++){int xx = v[k][j];flag[xx]--;if (flag[xx] == 0)dfs(xx);}}


0 0
原创粉丝点击