【学习笔记】双向(折半)搜索 meet in the middle

双向搜索

怎么觉得我的博客没什么正经算法啊。

坑,待填。

P4799 [CEOI2015 Day2] 世界冰球锦标赛

Code

#include<cstdio>
#include<algorithm>

#define LL long long

using namespace std;

const int MAXN = 45, MAXM = 1 << 21;
int n, mid, cnt_l, cnt_r;
LL m, ans;
LL ticket[MAXN] ,sum_l[MAXM], sum_r[MAXM];

void dfs(int l, int r, LL tot, LL *sum, int &cnt){
    if(tot > m) return;
    if(l > r){
        sum[++cnt] = tot;
        return;
    } 

    dfs(l + 1, r, tot, sum, cnt);
    dfs(l + 1, r, tot + ticket[l], sum, cnt);
}

inline LL read(){
    LL x = 0, f = 1;
    char c = getchar();

    while(c < '0' || c > '9'){
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9'){
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }

    return x * f;
}

int main(){
    n = read(), m = read();
    for(register int i = 1; i <= n; i++)
        ticket[i] = read();
    
    mid = n >> 1;
    dfs(1, mid, 0, sum_l, cnt_l);
    dfs(mid + 1, n, 0, sum_r, cnt_r);

    sort(sum_l + 1, sum_l + 1 + cnt_l);
    for(register int i = 1; i <= cnt_r; i++)
        ans += upper_bound(sum_l + 1, sum_l + 1 + cnt_l, m - sum_r[i]) - sum_l - 1;

    printf("%lld", ans);

    return 0;
}
posted @ 2022-08-19 11:59  TSTYFST  阅读(23)  评论(0编辑  收藏  举报