#include <iostream>
#include <array>
#include <map>
#include <algorithm>
#include <vector>
#include <numeric>
#include <cassert>
int main() {
  int n, m;
  std::cin >> n >> m;
  std::vector<int> as(n), bs(m);
  for (int& a : as) std::cin >> a;
  for (int& b : bs) std::cin >> b;
  
  std::ranges::sort(bs);
  std::vector<std::vector<int>> dp(m, std::vector<int>(1001));
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < 1001; ++j) {
      if (i == 0) dp[i][j] = j == 0 or j == bs[i];
      else {
        dp[i][j] = dp[i - 1][j];
        if (bs[i] <= j) dp[i][j] += dp[i - 1][j - bs[i]];
      }
    }
  }
  
  std::ranges::sort(as), std::ranges::sort(bs, std::greater<int>());
  
  std::map<std::array<int, 21>, bool> table;
  auto brute = [&](auto&& self, const std::array<int, 21>& state, int a_sum, int b_sum) -> bool {
    /*
    std::cout << "brute a_sum=" << a_sum << " b_sum=" << b_sum
              << " " << state[0]
              << " " << state[19] << " " << state[20] << "\n";
    // */
    if (table.contains(state)) return table[state];
    if (b_sum < a_sum) {
      return table[state] = false;
    }
    if (state[0] == m) {
      return table[state] = (a_sum == 0);
    }
    std::array<int, 21> new_state = state;
    int b = bs[new_state[0]]; ++new_state[0];
    for (int i = 20; i >= 1; --i) {
      if (new_state[i] != 0 and new_state[i] < bs[m-1]) {
        return table[state] = false;
      }
      if (0 == dp[m - 1 - b][new_state[i]]) {
        return table[state] = false;
      }
      if (b > new_state[i]) break;
      new_state[i] -= b;
      int j = i;
      for (; j > 1 and new_state[j-1] > new_state[j]; --j) {
        std::swap(new_state[j-1], new_state[j]);
      }
      if (self(self, new_state, a_sum - b, b_sum - b)) { return table[state] = true; }
      for (; j != i; ++j) {
        std::swap(new_state[j+1], new_state[j]);
      }
      new_state[i] += b;
    }
    if (self(self, new_state, a_sum, b_sum - b)) {
      return table[state] = true;
    }
    return table[state] = false;
  };
  
  std::array<int, 21> state{};
  //for (int i = 0; i < n; ++i) state[i] = as[i];
  //std::ranges::sort(state);
  //assert(state[20] == as[n-1]);
  for (int i = 1; i <= n; ++i) state[21-i] = as[n-i];
  int a_sum = std::accumulate(as.begin(), as.end(), 0);
  int b_sum = std::accumulate(bs.begin(), bs.end(), 0);
    //assert(b_sum == std::accumulate(bs.begin() + state[0], bs.end(), 0));
    //assert(a_sum == std::accumulate(state.begin() + 1, state.end(), 0));
  bool ans = brute(brute, state, a_sum, b_sum);
  std::cout << (ans ? "YES\n" : "NO\n");
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |