其他分享
首页 > 其他分享> > 【搜索】双向DFS

【搜索】双向DFS

作者:互联网

双向DFS


Acwing 171. 送礼物

题解:AcWing 171. 送礼物

AC代码:

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
const int N = 47;

int n;
LL w;
LL tmp[16777216]; int pos;
LL ans = 0;
int a[N];

void dfs1(int u, int now)
{
    if(u == n / 2){
        tmp[pos ++ ] = now;
        return ;
    }

    dfs1(u + 1, now);
    if((LL)now + a[u] <= w) dfs1(u + 1, now + a[u]);
}

void dfs2(int u, int now)
{
    if(u == n){
        int p = upper_bound(tmp, tmp + pos, w - now) - tmp;
        p -- ;

        if(p != -1) ans = max(ans, (LL)now + tmp[p]);

        return ;
    }
    
    dfs2(u + 1, now);
    if((LL)now + a[u] <= w) dfs2(u + 1, now + a[u]);
}

int main()
{
    cin >> w >> n;
    for(int i=0; i<n; i++) cin >> a[i];

    sort(a, a + n, greater<int>());
    reverse(a + n / 2, a + n);

    dfs1(0, 0);

    sort(tmp, tmp + pos);
    pos = unique(tmp, tmp + pos) - tmp;

    dfs2(n / 2, 0);

    cout << ans;


    system("pause");
    return 0;
}

标签:tmp,int,LL,pos,DFS,搜索,双向,now,171
来源: https://blog.csdn.net/weixin_51948235/article/details/121344489