hznu 1441 Greatest Number(选出4个数,使值最接近m)

来源:互联网 发布:分开旅行 知乎 编辑:程序博客网 时间:2024/06/05 19:36

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 1010020 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 longusing 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;}


0 0
原创粉丝点击