一文看懂蓝桥杯23真题买瓜

本文介绍了如何使用深度优先搜索(DFS)解决蓝桥杯竞赛中的买瓜问题,提供了原始暴力搜索代码并进行了100分优化,使用了二分查找技术来提高效率。
摘要由CSDN通过智能技术生成

一文看懂蓝桥杯23真题买瓜

dfs 深搜暴力70分代码

请添加图片描述

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
#define int long long
int n,m,a[50],ans=50;
//x当前瓜的序号,s当前已选瓜的重量,s当前劈的数量
void dfs(int x,int s,int cnt){
    if(s==m){
      ans=cnt;
      return;
    }
    if(x>=n||s>m||cnt>n)return;
    dfs(x+1,s,cnt);//不选
    dfs(x+1,s+a[x]/2,cnt+1);//选+劈
    dfs(x+1,s+a[x],cnt);//选+不劈
}
signed main(){
    cin>>n>>m,m*=2;
    for(int i=0;i<n;i++)cin>>a[i],a[i]*=2;
    dfs(0,0,0);
    cout<<(ans==50?-1:ans);
}

100分优化代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

#define x first
#define y second

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

const int N = 35;

int n, m, tn, t;
int w[N];
int res = 50;
PII alls[1 << 21];

void dfs_1(int u, LL s, int cnt)
{
    if (s > m)
        return;
    if (u == tn)
    {
        alls[t ++] = {s, cnt};
        return;
    }
    
    dfs_1(u + 1, s, cnt);
    dfs_1(u + 1, s + w[u], cnt);
    dfs_1(u + 1, s + w[u] / 2, cnt + 1);
}

void dfs_2(int u, LL s, int cnt)
{
    if (s > m || cnt >= res)
        return;
    if (u == n)
    {   
        int l = 0, r = t - 1;
        while (l < r)
        {
            int mid = l + r >> 1;
            if (alls[mid].x + s >= m)
                r = mid;
            else
                l = mid + 1;
        }
        
        if (alls[l].x + s == m)
            res = min(res, alls[l].y + cnt);
        
        return;
    }
    
    dfs_2(u + 1, s, cnt);
    dfs_2(u + 1, s + w[u], cnt);
    dfs_2(u + 1, s + w[u] / 2, cnt + 1);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    cin >> n >> m, m *= 2;
    for (int i = 0; i < n; ++ i )
        cin >> w[i], w[i] *= 2;
    
    sort(w, w + n);
    
    tn = max(0, n / 2 - 2);
    
    dfs_1(0, 0, 0);
    
    sort(alls, alls + t);
    int k = 1;
    for (int i = 1; i < t; ++ i )
        if (alls[i].x != alls[i - 1].x)
            alls[k ++] = alls[i];
    t = k;
    
    dfs_2(tn, 0, 0);
    
    cout << (res == 50? -1: res) << endl;
    
    return 0;
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值