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
思路:老板打算给员工们发奖励,但是员工会去存在一些要求,例如,输入a b 即a员工的奖励要比b员工的奖励多。老板决定每个员工的最低奖励为888元。老板想要知道自己最少需要多少钱俩奖励员工。所以最低工资为888,它的上一层的工资就是889,反向拓扑方便计算工资,先找出最低的那个在往上求。
#include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
vector <int> map[10005];
int in[10005];
int topo[10005];
int cnt;
int n, m,i,ans;
int money[10005];
int toposport() {
ans = 0;
queue<int> q;
cnt = 0;
int num=0;
for (i = 1; i <= n; i++) {
if (in[i] == 0) {
money[i] = 888;
q.push(i);
num++;
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (i = 0; i < map[u].size(); i++) {
int v = map[u][i];
in[v]--;
if (in[v] == 0) {
num++;
q.push(v);
money[v] = money[u] + 1;
}
}
if (num == n) {
for (i = 1; i <= n; i++) {
ans += money[i];
}
return ans;
}
}
return -1;
}
int main() {
while (scanf("%d %d", &n, &m) != EOF) {
memset(in, 0, sizeof(in));
memset(money, 0, sizeof(money));
for (i = 0; i <= n; i++) {
map[i].clear();
}
while (m--) {
int a, b;
scanf("%d %d", &a, &b);
map[b].push_back(a);
in[a]++;
}
int z = toposport();
printf("%d\n", z);
}
return 0;
}
来源:CSDN
作者:实在不知道什么
链接:https://blog.csdn.net/weixin_43813718/article/details/104143917