山东第一届省赛 Greatest Number(优雅暴力+二分)

前言

不愧是第一届省赛,题果然够难,这题wa了15次都没过,一点思路都没;

题目描述:

Saya likes math, because she think math can make her cleverer.

One day, Kudo invited a very simple game:

Given N integers, then the players choose no more than four integers from them (can be repeated) and add them together. Finally, the one whose sum is the largest wins the game. It seems very simple, but there is one more condition: the sum shouldn’t larger than a number M.

Saya is very interest in this game. She says that since the number of integers is finite, we can enumerate all the selecting and find the largest sum. Saya calls the largest sum Greatest Number (GN). After reflecting for a while, Saya declares that she found the GN and shows her answer.

Kudo wants to know whether Saya’s answer is the best, so she comes to you for help.

Can you help her to compute the GN?

大意:有多组数据,每组数据给出N个数,在这N个数里可重复的选择四个数使得最终的加和最接近M;

分析:

首先排除dfs,数据太大了
其次也不是纯暴力,多组数据还是每组最大1000个数
这时候我就错误的想到了多重背包(我觉得实在太像了),但是敲完了一分析还不是多重背包,因为是总共选四个,跟多重背包只是像而已

在结束后看了题解后,发现是一个巧妙的暴力+二分

1.总共有最多1000个数,首先读的时候就先筛一遍,把所有的大于M的数筛掉,这样读进来的数都是有用的;

2.其次做一个O(n2)的处理,把所有符合第一步条件的数两两相加,得到的数进行筛选再次存到数组里,这时数组里存的就是(选一次+选两次)的组合

3.这时候其实我们再用一次上面的操作得到的就是(选一次+选两次+选三次+选四次)的组合,但是会TLE,所以这时候我们要把O(n2)优化成O(nlogn),logn的实现就要请到我们的二分算法来实现;

先上代码:

#include<bits/stdc++.h>
using namespace std;
 
typedef unsigned long long ull;
typedef long long ll;
 
const ll maxx = 1e18;
const int N = 1e7+100;
const int p = 1e4;
const double eps = 1e-8;

ll n,m;
int a[N],t,cnt;
ll cnts;

int main()
{
	while(cin>>n>>m) 
	{
		if(m==0||n==0) return 0;//结束条件
		
		a[0]=0;cnt=0;//初始化
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&t);
			if(t<=m) a[++cnt]=t;	
		}//读入筛选
		
		int cnt1=cnt;
		
		for(int i=0;i<=cnt1;i++)
		{
			for(int j=0;j<=cnt1;j++)
			{
				if(a[i]+a[j]<=m) a[++cnt]=a[i]+a[j];
			}
		}//选一次+选两次
		
		sort(a+1,a+1+cnt);//排序,二分需要数组有序
		int max1=0;
		
		for(int i=0;i<=cnt;i++)
		{
			int l=i,r=cnt;//二分,注意左边界是 i
			
			while(l<=r)
			{
				int mid=(l+r)/2;
				if(a[mid]>m-a[i])
					r=mid-1;
				else
				{
					max1=max(max1,a[i]+a[mid]);
					l=mid+1;
				}
			}
		}
		
		printf("Case %lld: ",++cnts);
		printf("%lld\n\n",max1);
		
		
	}	
}

我们还没有解决从(选一次+选两次)到(选一次+选两次+选三次+选四次)这个问题,这时候二分就很好的解决了,我们把二分的对象从 M 变成 M-a[ i ],这时候去二分寻找一个小于等于 M-a[ i ] 的值 ,就完成了上述的转化,也就完成了最多选四个数的目标,即为最后的解法

总结:
这个解法真的非常巧妙,也非常的优雅,先对数组进行了筛选和处理,再进行了二分,思路非常巧妙,非常值得学习;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天都想发疯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值