Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2658 Accepted Submission(s): 771
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
Sample Output
题目大意:农场主要给大家发工资,但是工人们会有比较,农场主想要合理(不引发争吵)和发出的工资最少。给出1 2表示1 的工资一定要比2高。
解题思路:拓扑排序,但是要注意的是关系矩阵要简化, 否则超内存。
#include<stdio.h>
#include<string.h>
#define N 10005
#define MIN 887
int n, m, ok, sum;
int map[N][100], vis[N], value[N], in[N];
int topo(int k){
vis[k] = 1;
int max = MIN;
for (int i = 0; i < in[k]; i++){
if (vis[map[k][i]])
return 0;
else{
value[map[k][i]] = topo(map[k][i]);
if (value[map[k][i]] == 0)
return 0;
if (max < value[map[k][i]])
max = value[map[k][i]];
}
}
vis[k] = 0;
value[k] = max + 1;
return value[k];
}
int main(){
while (scanf("%d%d", &n, &m) != EOF){
// Init.
memset(map, 0, sizeof(map));
memset(value, 0, sizeof(value));
memset(in, 0, sizeof(in));
ok = sum = 0;
// Read.
for (int i = 0; i < m; i++){
int a, b;
scanf("%d%d", &a, &b);
map[a][in[a]++] = b;
}
// Handle.
for (int i = 1; i <= n; i++){
if (value[i]){
sum += value[i];
continue;
}
memset(vis, 0, sizeof(vis));
value[i] = topo(i);
if (value[i] == 0){
ok = 1;
break;
}
sum += value[i];
}
// Printf.
if (ok)
printf("-1\n");
else
printf("%d\n", sum);
}
return 0;}