HDU:2647 Reward(链表型拓扑排序)

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7523    Accepted Submission(s): 2373


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
 

Author
dandelion
 

Source
 

Recommend
yifenfei

题目大意:快过年了,老板要给员工们发年终奖,员工个数为n,但是这些员工们有m条愿望,下面m行,每行输入a b,代表a的奖金比b多,怎么才能使老板花费最少并且满足所有的愿望呢?最低员工的年终奖金为888元,如果不能满足所有愿望,输出-1。
解题思路:用链表来拓扑排序,如果不能满足的话说明其中有环,判断处理顶点的个数与总数是否相等即可判断是否有环。
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
	int to,next;
}bian[20010];
int in[10010];
int n,m;
int head[20010];
int money[10010];
void tuopu()
{
	queue<int>q;
	memset(money,0,sizeof(money));
	for(int i=1;i<=n;i++)
	{
		if(in[i]==0)//度数为0(无要求的员工888元) 
		{
			q.push(i);
			money[i]=888;
		}
	}
	int sum=0;//记录处理的节点的个数 
	while(!q.empty())
	{
		int tmp=q.front();
		q.pop();
		sum++;
		for(int i=head[tmp];i!=-1;i=bian[i].next)
		{
			in[bian[i].to]--;//将与tmp连接的点的度数都减一 
			if(in[bian[i].to]==0)//一旦度数为0 则加入队列 
			{
				money[bian[i].to]=money[tmp]+1;//要最节省,所有他最多是他前面元素的钱数+1 
				q.push(bian[i].to);
			}
		}
	}
	if(sum!=n)//判断是否成环 
	{
		printf("-1\n");
	}
	else
	{
		int ans=0;
		for(int i=1;i<=n;i++)
		{
			ans=ans+money[i];
		}
		printf("%d\n",ans);
	}
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		memset(head,-1,sizeof(head));//初始化表头 
		memset(in,0,sizeof(in));//初始化入读 
		for(int i=0;i<m;i++)
		{
			int a,b;
			scanf("%d%d",&a,&b);
			bian[i].to=a;//a约束着b,所以在树中,a在b的右端 
			bian[i].next=head[b];
			head[b]=i;
			in[a]++;
		}
		tuopu();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值