G

来源:互联网 发布:盗号软件 编辑:程序博客网 时间:2024/04/29 05:20

Description

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?

Input

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
 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.

Output

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.

Sample Input

2 1010020 0

Sample Output

Case 1: 8

解题思路:
题意为从输入的数中,最多找4个数(可重复)使它们的和在小于给定M的前提下最大,具体思路为把输入的符合条件的数存入数组中,然后用两层循环把所有数(包括数和它本身)的两两组合放入数组sum中,然后排序,用二分查找取两个2组合(sum的项)相加,求出最大值。但注意到,并不一定非要取4个数,取1,2,3,4个数都可以,这也是比较难的地方,这就要求让sum中出现0,1,2组合,这样任取两个sum便能得到1,2,3,4组合,方法为:令temp[0]=0;即sum[0]=temp[0]+temp[0]=0为0组合。temp[i]+temp[0]为1组合

细节处理:

注意i和j的迭代方式

代码:

#include <iostream>#include<string>#include<cstring>#include<vector>#include<algorithm>int temp[1009];int sum[1000009];using namespace std;int main(){    int m,n,i,j;    int num=0;    while(cin>>n>>m&&(n||m))    {        num++;        temp[0]=0;        int r,x=1;        for(i=1;i<=n;i++)        {cin>>r; if(r<=m) temp[x++]=r;}        int k=0;        for(i=0;i<x;i++)        for(j=i;j<x;j++)        if(temp[i]+temp[j]<=m) sum[k++]=temp[i]+temp[j];        sort(sum,sum+k);        int mid,left,right,max=0;        for(i=0;i<k;i++)        {            left=i,right=k-1;            while(left<=right)            {                mid=(left+right)/2;                if(sum[i]+sum[mid]>m)                    right=mid-1;                else                {                    if(max<sum[i]+sum[mid])                        max=sum[i]+sum[mid];                    left=mid+1;                }            }        }        cout<<"Case "<<num<<": "<<max<<endl;        cout<<endl;    }    return 0;}


 

0 0
原创粉丝点击