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?
输入
The input consists of several test cases.
The first line of input in each test case contains two integers N (0<N≤1000) and M(0<M≤ 1000000000), which represent the number of integers and the upper bound.
Each of the next N lines contains the integers. (Not larger than 1000000000)
The last case is followed by a line containing two zeros.
输出
For each case, print the case number (1, 2 …) and the GN.
Your output format should imitate the sample output. Print a blank line after each test case.
样例输入
2 10
100
2
0 0
样例输出
Case 1: 8
http://hsacm.cn/JudgeOnline/problem.php?cid=1009&pid=6
可以把这四个数分成对等的两部分,这样存的数组最大也就1000*1000(晕,我当时以为是10^8然后一直内存超限……)
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<cstdio>
#define ll long long
using namespace std;
int n,m;
int x[1001];
int y[1000001];
int main(){
int cnt=0;
while(scanf("%d%d",&n,&m)&&(n!=0||m!=0)){
for(int i=0;i<n;++i){
scanf("%d",&x[i]);
}
int p=-1;
for(int i=0;i<n;++i){
for(int j=0;j<n;++j)
y[++p]=x[i]+x[j];
}
sort(y,y+p+1);
int q=unique(y,y+p+1)-y;
int s=0;
for(int i=0;i<q;++i){ //疏忽,比赛时这里写成了q/2
for(int j=q-1;j>=0;--j){
if(y[i]+y[j]<=m){
s=max(s,y[i]+y[j]);
break;
}
}
}
printf("Case %d: %d\n\n",++cnt,s);
}
return 0;
}
本文探讨了数学游戏中如何寻找最优解,通过实例分析和算法实现,解释了如何利用有限整数集合找到最大和不超过特定上限的组合。重点介绍了枚举方法及优化策略。
1549

被折叠的 条评论
为什么被折叠?



