hsacm-1441

来源:互联网 发布:java简单图书系统代码 编辑:程序博客网 时间:2024/06/06 10:52


http://hsacm.cn/JudgeOnline/problem.php?cid=1009&pid=6

题目描述

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

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


这题数据结构课上老师讲过的。最暴力的想法是四个FOR循环,可是其实没有必要用四个,用两个循环就能找到两个数相加的所有情况放进数组Num,那么最后再用次循环吧NUM数组里面的数遍历两个进行相加就是四个数相加的结果了不是吗?

#include <iostream>#include <cstdio>#include <cmath>#include <vector>#include <cstring>#include <algorithm>#include <string>#include <set>#include <functional>#include <numeric>#include <sstream>#include <stack>#include <map>#include <queue>using namespace std;long long num[1000100];int main(){    long long n,m;    long long p=1;    while(cin >> n >> m)    {        if(n==0&&m==0)break;        memset(num,0,sizeof(num));        long long a[1010];        for(int i=0;i<n;i++)        {            cin >> a[i];        }        long long k=0;        for(int i=0;i<n;i++)        {            for(int j=i;j<n;j++)            {                num[k++]=a[i]+a[j];            }        }         sort(num,num+k);        long long ans=0;        for(int first=0;first<k;first++)        {            if(num[first]>m)break;            for(int second = k-1;second>=0;second--)            {                if(num[first]+num[second]<=m)                {                ans=max(ans,num[first]+num[second]);                break;                }            }        }        cout<<"Case "<<p++<<": "<<ans<<endl<<endl;             }     return 0;}


0 0
原创粉丝点击