HDU 2647-Reward-拓扑排序+分层计数

本文介绍了一种使用拓扑排序算法解决奖金分配问题的方法。在满足特定条件的情况下,确保每位员工的奖金至少为888,并且遵循指定的奖金等级规则。通过逐层取出入度为0的节点,实现奖金的最小化分配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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个条件。
每个条件是两个整数a,b,代表两个人,要求a的奖金比b的奖金多。
并且每个人的奖金至少是888。
问奖金总额至少是多少。

核心思想:

拓扑排序。
每一次将所有入度为0的点一起取下,这些人的奖金数是一样的,都是前一批取下的人的奖金数+1。
一层一层的将点取下,全部取完就输出总额,无法取完(即含有环)就输出-1。

代码如下:

#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e4+10;
vector<int>vec[N];
int ru[N];
bool vis[N];
ll ans;
bool TuoPu(int n)
{
	queue<int>q;
	int cnt=0;
	ll z=888;
	while(1)
	{
		int flag=0;
		for(int i=1;i<=n;i++)
			if(!vis[i]&&ru[i]==0)
			{
				vis[i]=1;
				flag=1;
				q.push(i);
				cnt++;
			}
		if(!flag)
			break;
		ans+=z*q.size();
		z++;
		while(!q.empty())
		{
			int te=q.front();
			q.pop();
			int len=vec[te].size();
			for(int i=0;i<len;i++)
				ru[vec[te][i]]--;
		}
	}
	if(cnt<n)
		return 0;
	return 1;
}
int main()
{
	int n,m,x,y;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		//初始化 
		for(int i=1;i<=n;i++)
		{
			vec[i].clear();
			ru[i]=0;
			vis[i]=0;
		} 
		ans=0;
		//输入
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			ru[x]++;
			vec[y].push_back(x);
		}
		//拓扑并输出 
		if(!TuoPu(n))
			printf("-1\n");
		else
			printf("%lld\n",ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值