首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

问一路不难的题目~

2013-01-01 
问一道不难的题目~~~大家好,这道题怎么做? 就是找一个数组里和最大的几个数,但不能超过指定数。如下例,5是

问一道不难的题目~~~
大家好,这道题怎么做? 就是找一个数组里和最大的几个数,但不能超过指定数。如下例,5是数组里5个数字,21是和只能小于等于21.哪位能提供个思路?或来些伪代码都行,谢谢!

Input

The first line of input contains an integer N (3 ≤ N ≤ 100), the number of cards, and M (10 ≤ M ≤ 300 000), the number that we must not exceed.
The following line contains numbers written on Mirko?s cards: N distinct space-separated positive integers less than 100 000.
There will always exist some three cards whose sum is not greater than M.


Output

The first and only line of output should contain the largest possible sum we can obtain.


Sample Input
5 21 
5 6 7 8 9 

Sample Output
21


[解决办法]
你可以先对数组进行排序,在有序数组里面就好找了
[解决办法]
0-1背包问题,基础算法之一
[解决办法]
如果要求的选择的牌一定是3,就用3个for循环就行了
如果要求牌数不确定,用0-1背包
[解决办法]
0-1背包这样:(如果是要求3张牌,就直接用3个循环)


#include <stdio.h>
#include <string.h>

char b[300001];

int main()
{
int n,m,a,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(b,0,sizeof(b));
b[0]=1;
while(n--)
{
scanf("%d",&a);
for(i=m;i>=a;i--)
b[i]
[解决办法]
=b[i-a];
}
int ans;
for(i=m;i>=0;i--)
if(b[i])
{
ans=i;break;
}
printf("%d\n",ans);
}
}

热点排行