【NBUT】1651 - Red packet(二分)

这是一篇关于使用二分查找算法解决新年红包分配问题的博客。在新年期间,大老板Wine93要将一定金额的红包分给n个人,确保每个人都能得到整数元且至少有一位成为“幸运儿”。题目描述了已知k个人获得的红包金额,求在剩余的人中,至少需要得到多少红包金额才能成为“幸运儿”。文章提供了样例输入和输出,并指出二分查找的实现需要注意的条件是,剩下的人无论如何分配,当前人都必须是运气最好的。
摘要由CSDN通过智能技术生成

点击打开题目

  • [1651] Red packet

  • 时间限制: 1000 ms 内存限制: 65535 K
  • 问题描述
  • New Year is coming! Our big boss Wine93 will distribute some “Red Package”, just like Alipay and Wechat.

    Wine93 has m yuan, he decides to distribute them to n people and everyone can get some money(0 yuan is not allowed and everyone’s money is an integer), Now k people has gotten money, it’s your turn to get “Red Package”, you want to know, at least how much money to give you, then you can must become the “lucky man”. and the m yuan must be used out.

    Noting that if someone’s money is strictly much than others’, than he is “lucky man”.


  • 输入
  • Input starts with an integer T (T <= 50) denoting the number of test case.
    For each test case, three integers n, m, k (1 <= k < n <= 100000, 0< m <= 100000000) will be given.
    Next line contains k integers, denoting the money that k people get. You can assume that the k integers’ summation is no more than m.
  • 输出
  • Ouput the least money that you need to become the “lucky man”, if it is impossible, output “Impossible” (no quote).
  • 样例输入
  • 3
    3 5 2
    2 1
    4 10 2
    2 3
    4 15 2
    3 5
    
  • 样例输出
  • Impossible
    4
    6
    
  • 提示
  • 来源
  • 本站或者转载


刚开始二分的条件控制有错,应该是剩下的人无论怎么分这个人都是运气王。


代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
	int n,m,k;
	int maxx,sum;		//前面人钱最多的,总和 
	int rec;		//剩余分钱的人数 
	int money;		//剩余钱数 
	int u;
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%d %d %d",&n,&m,&k);
		maxx = sum = 0;
		for (int i = 1 ; i <= k ; i++)
		{
			int t;
			scanf ("%d",&t);
			maxx = max (maxx , t);
			sum += t;
		}
		rec = n-k-1;
		money = m - sum;
		if (money-rec <= maxx)
		{
			printf ("Impossible\n");
			continue;
		}
		if (rec == 0)		//注意这个 
		{
			printf ("%d\n",money);
			continue;
		}
		int l,r,mid;
		l = maxx + 1;
		r = money - rec;
		while (r >= l)
		{
			mid = (l + r) >> 1;
			if (money - mid - rec + 1 < mid)
				r = mid - 1;
			else
				l = mid + 1;
		}
		printf ("%d\n",l);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值