【模板】meet-in-the-middle算法

· · 算法·理论

meet-in-the-middle算法好像就是双向搜索

e.g P5691 [NOI2001] 方程的解数

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define CCH 0
using namespace std;

long long read() {
    register long long x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

long long n, m, K[10], p[10], cnt;
long long ans[5000000], eid, Ans;

long long quick_mi(long long a, long long b) {
    long long base = 1;
    for (; b; b >>= 1) {
        if (b & 1) base = base * a;
        a = a * a;
    }
    return base;
}

void dfs1(long long k, long long sum) {
    if (k == cnt + 1) {
        ans[++eid] = sum;
        return;
    }
    for (long long u = 1; u <= m; u++) {
        long long ans = K[k] * quick_mi(u, p[k]);
        dfs1(k + 1, sum + ans);
    }
}

void dfs2(long long k, long long sum) {
    if (k == n + 1) {
        long long x = lower_bound(ans + 1, ans + 1 + eid, -sum) - ans;
        long long y = upper_bound(ans + 1, ans + 1 + eid, -sum) - ans;
        if (x < y) Ans += (y - x);
        return;
    }
    for (long long u = 1; u <= m; u++) {
        long long ans = K[k] * quick_mi(u, p[k]);
        dfs2(k + 1, sum + ans);
    }
}

int main() {
    n = read(); m = read();
    for (long long i = 1; i <= n; i++) {
        K[i] = read();
        p[i] = read();
    }
    cnt = (1 + n) >> 1;
    dfs1(1, 0);
    sort(ans + 1, ans + 1 + eid);
    dfs2(cnt + 1, 0);
    printf("%lld\n", Ans);
    return CCH;
}