hdu 2647 Reward

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

题意:给定一个n代表人数,m代表有几个关系。。一下m行输入m个关系a ,b 代表 a拿到的工资要大于b。

每个人的工资最低是888.。要求最少要付出的工资是多少

思路:拓扑排序的简单应用。由于人数1W,不可能存成邻接矩阵,,关系只有2W,。直接存成邻接表。

用vector来存。然后就是简单的拓扑排序了。。不过值得注意的地方是。每次保存钱数的时候。一定要是最大的钱数才是符合条件的。。。

这题因为一个简单的下标错误让我WA了好几次还找不到 - -,,感觉自己简直2到不行了

#include<vector>  
#include<iostream>  
#include<algorithm>  
using namespace std;  

int n,m;
int a,b;  
int du[10005];
int money[10005];
int ren;
int sum;
int sb;
int max(int a, int b)
{
	if (a > b)
		return a;
	else
		return b;
}
int find()
{
	int i;
	for (i = 1; i <= n; i ++)
	{
		if (du[i] == 0)
		{
			sb = i;
			return 1;
		}
	}
	return 0;
}
void to(vector<int> map[])
{
	int i;
	while (find())
	{
		ren ++;
		du[sb] --;
		for (i = 0; i < map[sb].size(); i ++)
		{
			int t = map[sb][i];
			du[t] --;
			money[t] = max(money[t], money[sb] + 1);
		}
	}
}
int main()  
{  
	int i;
    while(scanf("%d%d", &n, &m) != EOF)  
    {  
		ren = 0;
		sum = 0;
		sb = 0;
        vector<int> map[10005];  
        memset(du, 0, sizeof(du));
		memset(money, 0, sizeof(money));
        while(m --)
        {
			scanf("%d%d", &a, &b);
			map[b].push_back(a);
			du[a] ++;
        }
		to(map);
		for (i = 1; i <= n; i ++)
			sum += money[i];
		if (ren == n)
			printf("%d\n", sum + 888 * n);
		else
			printf("-1\n");
    }  
    return 0;  
}


你可能感兴趣的:(hdu 2647 Reward)