题目:
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.
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.
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
题意:一个裸的拓扑排序,对于矛盾的情况就是某种状态不存在入度为0的点。具体拓扑排序实现见博客
HDU 1285--确定比赛名次。
实现:#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAX = 10005;
struct node {
int d, minmum;
}d[MAX];
int n, m;
vector <int> path[MAX];
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
for (int i = 1; i <= n; i++)
path[i].clear();
int v1, v2;
for (int i = 0; i < m; i++) {
scanf("%d%d", &v1, &v2);
path[v2].push_back(v1);
}
for (int i = 1; i <= n; i++) {
d[i].d = 0;
d[i].minmum = 888;
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < path[i].size(); j++) {
// cout << "ok " << path[i][j] << endl;
d[path[i][j]].d++;
}
}
int ans = 0;
int visit = 0;
int flag;
for (int ii = 0; ii < n; ii++) {
for (int i = 1; i <= n; i++) {
if (d[i].d == 0) {
ans += d[i].minmum;
d[i].d = -1;
flag = i;
visit++;
break;
}
}
for (int j = 0; j < path[flag].size(); j++) {
int kk = path[flag][j];
d[kk].d--;
d[kk].minmum = max(d[kk].minmum, d[flag].minmum + 1);//为了找到该人的最低工资
}
}
if (visit == n) {
printf("%d\n", ans);
}
else {
printf("-1\n");//有人剩余,入度且不为0
}
}
return 0;
}