天天看點

hdu 2647 Reward(拓撲排序+鄰接表) Reward

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

2 1
1 2
2 2
1 2
2 1
        

Sample Output

1777
-1
        

  題目大意:農場主要給大家發工資,但是勞工們會有比較,農場主想要合理(不引發争吵)和發出的工資最少。給出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;}