DFS技巧 折半搜索

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<queue>
#include<stack>
#include<sstream>
#include<cstdio>
#define INF 0x3f3f3f3f
//const int maxn = 1e6 + 5;
const double PI = acos(-1.0);
typedef long long ll;
using namespace std;

int n, t;
int sum, tmp;
int a[50];

bool found;
map<int, int> mp;

void dfs1(int h, int t) {
    if (h > t) {
        mp[tmp] = 1;
        return;
    }
    dfs1(h + 1, t);
    tmp += a[h];
    dfs1(h + 1, t);
    tmp -= a[h];
}

void dfs2(int h, int t) {
    if (h > t) {
        if (mp[sum - tmp]) found = 1;
        return;
    }
    dfs2(h + 1, t);
    tmp += a[h];
    dfs2(h + 1, t);
    tmp -= a[h];
}

int main() {
    scanf("%d%d", &n, &sum);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    dfs1(1, n / 2);
    dfs2(n / 2 + 1, n);
    printf(found ? "YES" : "NO");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hznumqf/p/12361634.html
今日推荐