洛谷 P4674 [BalticOI 2016 day1]Bosses bfs

题目描述
A company of nn employees is due for a restructuring. In the resulting hierarchy,represented as a rooted tree, every node will be the boss of its children.

Each employee has a list of bosses they will accept. In addition, all employees mustbe assigned a salary. The salary must be a positive integer, and the salary of eachboss must be larger than the sum of salaries of their immediate subordinates.

Your task is to structure the company so that all above conditions hold, and the sumof all the salaries is as small as possible.

输入格式
The first input line contains an integer nn : the number of employees. The employees are numbered 1,2,…,n.After this, the input contains nn lines that describe the preferences of the employees.The iith such line contains an integer k_i, followed by a list of k_i integers. The list consists of all employees that the iith employee accepts as their boss.

输出格式
You should output the lowest total salary among all valid restructurings. You can assume that at least one solution exists.

题意翻译
[BalticOI 2016 Day1]上司们

题目描述
某公司有 nn 个职员,其职员之间的阶级关系可以用一棵有根树表示,每个结点都是其所有儿子的上司。
每个职员应当分配一个工资。工资是一个正整数,且每个上司的工资必须大于它所有直系下属的工资之和。
你的任务是找到一种工资分配方案,使得以上所有条件满足且工资之和尽量小。

输入格式
第一行包含一个整数 nn,表示职员的个数,职员依次编号为1,2,…,n。
接下来 n 行,第 ii 行包含一个整数 k_i ,以及一个包含 k_i个数的数列。这个数列表示第 i 个员工的所有下属。

输出格式
输出所有方案中最小的工资之和,数据保证有解。

由 @I_love_him52 提供翻译

输入输出样例
输入 #1
4
1 4
3 1 3 4
2 1 2
1 3
输出 #1
8

解法:bfs

  • 我们对于每一个节点都枚举一次,然后把每个节点都推入队列求出深度,然后和ans取更小值就可以了

  • 注意细节,我们需要反向建边,因为上司的工资应该是最大的,所以我们这样之后,员工的深度就会小于上司

AC代码

#include<cstdio>
#include<queue>
#include<cstring>
#define inf 0x3f3f3f3f
#define re register int
using namespace std;
struct edge {
	int nex,to;
}e[50005];
int n,cnt,ans=inf,head[5005],d[5005];
queue<int> q;
inline int read() {
	int x=0,cf=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') {
		if(ch=='-') cf=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') {
		x=(x<<3)+(x<<1)+(ch^48);
		ch=getchar();
	}
	return x*cf;
}
inline int min(int A,int B) { return A<B?A:B; }
inline void add(int x,int y) {
	e[++cnt].to=y,e[cnt].nex=head[x],head[x]=cnt;
}
inline void bfs(int s) {
	memset(d,0,sizeof(d));
	d[s]=1; q.push(s);
	while(q.size()) {
		int x=q.front(); q.pop();
		for(re i=head[x];i;i=e[i].nex) {
			int y=e[i].to;
			if(d[y]) continue;
			d[y]=d[x]+1;
			q.push(y);
		}
	}
	int tot=0;
	for(re i=1;i<=n;i++) {
		if(!d[i]) return;//如果有的节点不能到达直接返回
		tot+=d[i];
	}
	ans=min(ans,tot);
	return;
}
int main() {
	n=read();
	for(re i=1;i<=n;i++) {
		int k=read();
		for(re j=1;j<=k;j++) {
			int y=read();
			add(y,i);
		}
	}
	for(re i=1;i<=n;i++) {
		bfs(i);
	}
	printf("%d",ans);
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值