ACM: hdu 2647 Reward -拓扑排序

hdu 2647 Reward

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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

/*/
题意:
老板发工资,但是老板很小气,但是至少每个人得发888元,而且,每个员工之间有业绩比较,业绩高的工资得高,至少多1元,问至少要发多少钱。

思路:
拓扑排序,查找有多少个不同等级的点,每个点的值与前面累加1;

计总和加上每个人888.

简单的拓扑排序,没必要多说了:

AC代码:
/*/

#include"algorithm"
#include"iostream"
#include"cstring"
#include"cstdlib"
#include"string"
#include"cstdio"
#include"vector"
#include"cmath"
#include"queue"
using namespace std;
#define memset(x,y) memset(x,y,sizeof(x))
#define memcpy(x,y) memcpy(x,y,sizeof(x))
#define MX 10005

int indegree[MX];
vector<int>next_v[MX];

void init() {
	for(int i=0; i<MX; i++)
		next_v[i].clear();
	memset(indegree,0);
}

int toposort(int n) {
	int p[MX];
	int cnt=0,money=0,num,summoney=n*888 ;
	while(cnt!=n) {
		num=0;
		for(int i=1; i<=n; i++) {
			if(!indegree[i]) {
				indegree[i]=-1;
				p[num]=i;
				num++;
			}
		}
		if(!num) {//没有员工,工资最高,不能排序,返回错误;
			return -1;
		} else {
			summoney+=money*num;
			money++;
			cnt+=num; //表示已经历遍了这么多个员工
			for(int i=0; i<num; i++) {
				for(int  j=0; j<next_v[p[i]].size(); j++) {
					indegree[next_v[p[i]][j]]--;
				}
			}
		}
	}
	return summoney;
}

int main() {
	int n,m,a,b;
	while(~scanf("%d%d",&n,&m)) {
		init();
		for(int qq=0; qq<m; qq++) {
			scanf("%d%d",&a,&b);
			int flag=0;
			for(int i=0; i<next_v[b].size(); i++) {
				if(next_v[b][i]==a)
					flag=1;
			}
			if(!flag) {
				indegree[a]++;
				next_v[b].push_back(a);
			}
		}
		printf("%d
",toposort(n));
	}
	return 0;
}
  
原文地址:https://www.cnblogs.com/HDMaxfun/p/5741860.html