hdu3448Bag Problem 暴力枚举

//给k个数,问最多取n个,所取的数的和不大于m的最大的和
//暴力枚举所有情况
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std ;
const int maxn = 110 ;
typedef int ll;
ll ans = 0 ;
ll a[maxn] ;
ll n , m ;
int k ;
void dfs(int pos , int num , int  sum)
{
    ans = max(ans ,sum) ;
    if(pos == k + 1)return ;
    dfs(pos + 1 , num , sum) ;
    if(sum + a[pos] <= m && num + 1 <= n)
    dfs(pos + 1 , num + 1 , sum + a[pos]) ;
}
int main()
{
    while(~scanf("%d%d" ,&n , &m))
    {
        scanf("%d" , &k ) ;
        for(int i = 1;i <= k;i++)
        scanf("%d" ,&a[i]) ;
        sort(a+1 , a+1+k) ;
        int sum = 0 ;
        for(int i = k;i >= k - n + 1 ; i --)
        sum += a[i] ;
        if(sum <= m){cout<<sum<<endl;continue ;}
        ans = 0 ;
        dfs(1 , 0 , 0) ;
        cout<<ans<<endl;
    }
}

你可能感兴趣的:(暴力)