CODEVS 2144 砝码称重2

//二分dfs,最后合并 
#include<bits/stdc++.h>
using namespace std;
const int maxn = 400000; 
int n, m, tot1, tot2, a[31];
int ans = 0x3f3f3f3f;
struct node{
    int num, w;
} hash1[maxn], hash2[maxn];

bool cmp(node p, node q){
    return p.w < q.w;
}

void dfs1(int haoyu, int step, int mnow){
    if(haoyu > n/2) return;
    hash1[++tot1].num = step + 1;
    hash1[tot1].w = mnow + a[haoyu];
    //if(hash1[tot1].w == m)    ans = hash1[tot1].num;
    dfs1(haoyu+1, step+1, mnow+a[haoyu]);
    dfs1(haoyu+1, step, mnow);
}

void dfs2(int haoyu, int step, int mnow){
    if(haoyu > n)   return;
    hash2[++tot2].num = step + 1;
    hash2[tot2].w = mnow + a[haoyu];
    //if(hash2[tot2].w == m)    ans = hash2[tot2].num;
    dfs2(haoyu+1, step+1, mnow+a[haoyu]);
    dfs2(haoyu+1, step, mnow);
}

int find(int x){//二分查找代码要记牢,左开右闭 
    int l = 1, r = tot2+1, mid = l + (r-l)/2;
    while(l < r){
        if(x < hash2[mid].w){ r = mid; mid = l + (r-l)/2; }
        if(x > hash2[mid].w){ l = mid + 1; mid = l + (r-l)/2; }
        if(x == hash2[mid].w)   return mid;
    }
    return -1;
}

int main(){
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
        cin >> a[i];
    sort(a+1, a+n+1);
    dfs1(1, 0, 0);
    sort(hash1+1, hash1+tot1+1, cmp);
    dfs2(n/2+1, 0, 0);
    sort(hash2+1, hash2+tot2+1, cmp);
    for(int i = 0; i <= tot1; i++){//从0开始是因为有可能前半段没有目标砝码,全在后半段,如果从1开始就找不到后半段的了 
        int flag = find(m - hash1[i].w);
        if(flag != -1){
            ans = min(hash1[i].num + hash2[flag].num, ans);
        }
    }
    cout << ans << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值