Watashi's BG

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4778

当存在一个sum+(s[N]-s[h-1])恒不大于M时return掉

View Code
const int MM = 111111;
#define debug puts("wrong")
typedef long long int64;
int N,M,ans;
int s[MM];
int num[MM];
bool cmp(int x,int y) {return x>y;}
void get_data() {
    int i,j,k;
    s[0]=0;
    for(i=1;i<=N;i++) {
        scanf("%d",&num[i]);
    }
    sort(num+1,num+N+1,cmp);
    for(i=1;i<=N;i++)     s[i]=s[i-1]+num[i]; 
}
void dfs(int h,int sum) {
    if(sum>M || ans==M) return;
    if(h>N) {ans=f_max(sum,ans);return;} 
    if(sum==M) {ans=M;return;}
    if(sum+(s[N]-s[h-1])<=M) {
        ans=f_max(ans,sum+(s[N]-s[h-1]));
        return;
    }    
    dfs(h+1,sum);
    dfs(h+1,sum+num[h]);
}
void solve() {
    int i,j,k;
    ans=-1;
    dfs(1,0);
    printf("%d\n",ans);
}
int main() {
    while(scanf("%d%d",&N,&M)!=EOF) get_data(),solve();
    return 0;
}  

 

posted @ 2013-04-17 12:43  zhang1107  阅读(186)  评论(0编辑  收藏  举报