Problem p02648 (C++) — buggy submission, verdict: Time Limit Exceeded

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define REP(i, N) for (int i = 0; i < (N); ++i)

void chmax(int &a, const int b) {
  if (a < b)
    a = b;
}

// 1-indexed!!!

const int MX = (1 << 18) + 10;
const int MV = 100010;
int N, Q;
int V[MX], W[MX];

const int TH = 11;
int dp[(1 << TH) + 10][100100];
void prepare(int v) {
  int v_tmp = v;
  int n = 0;
  vector<int> a_v, a_w;
  while (v > 0) {
    ++n;
    a_v.emplace_back(V[v]);
    a_w.emplace_back(W[v]);
    v >>= 1;
  }
  REP(i, 1 << n) {
    int val = 0, wei = 0;
    REP(j, n) if (i & (1 << j)) {
      val += a_v[j];
      wei += a_w[j];
      if (wei > MV)
        break;
    }
    if (wei > MV)
      continue;
    chmax(dp[v_tmp][wei], val);
  }
  REP(i, MV) chmax(dp[v_tmp][i + 1], dp[v_tmp][i]);
}

// memo done?
bool available(int v) { return v <= (1 << TH); }

void solve(int v, int l) {
  if (available(v)) {
    cout << dp[v][l] << endl;
    return;
  }
  int n = 0;
  vector<int> a_v, a_w;
  while (not available(v)) {
    ++n;
    a_v.emplace_back(V[v]);
    a_w.emplace_back(W[v]);
    v >>= 1;
  }
  int res = 0;
  REP(i, 1 << n) {
    int val = 0, wei = 0;
    REP(j, n) if (i & (1 << j)) {
      val += a_v[j];
      wei += a_w[j];
      if (wei > l)
        break;
    }
    if (wei > l)
      continue;
    chmax(res, dp[v][l - wei] + val);
  }
  cout << res << endl;
}

signed main() {
  cin >> N;
  REP(i, N) cin >> V[i + 1] >> W[i + 1];
  REP(i, 1 << TH) prepare(i + 1);
  cin >> Q;
  while (Q--) {
    int v, l;
    cin >> v >> l;
    solve(v, l);
  }
}


Error: TLE

Fixed submission:

#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#include <bits/stdc++.h>
using namespace std;
// #define int long long
// #define endl '\\n'

#pragma region TEMPLATE

/* TYPE */
typedef int ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<string> vst;
typedef vector<bool> vb;
typedef vector<ld> vld;
typedef vector<vector<int>> vvi;
template <typename T, typename Cmp = less<>>
using prique = priority_queue<T, vector<T>, Cmp>;
template <typename T> using prique_r = prique<T, greater<>>;
/* CONSTANT */
#define ln '\\n'
// const int INF = 1 << 30;    const ll INFF = 1LL << 60;  const string ALPHABET
// = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const int MOD = 1e9 + 7;    const int MODD =
// 998244353; const string alphabet = "abcdefghijklmnopqrstuvwxyz";
const double EPS = 1e-9;
const ld PI = 3.14159265358979323846264338327950288;
const int dx[] = {1, 0, -1, 0, 1, -1, -1, 1, 0};
const int dy[] = {0, 1, 0, -1, -1, -1, 1, 1, 0};
/* CONTAINER */
#define PB emplace_back
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define SORT(v) sort(ALL(v))
#define RSORT(v) sort(RALL(v))
#define LESS(x, val) (lower_bound(x.begin(), x.end(), val) - x.begin())
#define LEQ(x, val) (upper_bound(x.begin(), x.end(), val) - x.begin())
#define GREATER(x, val) (int)(x).size() - LEQ((x), (val))
#define GEQ(x, val) (int)(x).size() - LESS((x), (val))
#define UNIQUE(v)                                                              \\
  sort(ALL(v));                                                                \\
  (v).erase(unique(ALL(v)), (v).end())
template <typename T> vector<T> make_v(size_t a) { return vector<T>(a); }
template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) {
  return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}
template <typename T, typename U, typename... V>
enable_if_t<is_same<T, U>::value != 0> fill_v(U &u, const V... v) {
  u = U(v...);
}
template <typename T, typename U, typename... V>
enable_if_t<is_same<T, U>::value == 0> fill_v(U &u, const V... v) {
  for (auto &e : u)
    fill_v<T>(e, v...);
}
/* LOOP */
#define _overload3(_1, _2, _3, name, ...) name
#define _REP(i, n) REPI(i, 0, n)
#define REPI(i, a, b) for (ll i = (ll)a; i < (ll)b; ++i)
#define REP(...) _overload3(__VA_ARGS__, REPI, _REP, )(__VA_ARGS__)
#define _RREP(i, n) RREPI(i, n, 0)
#define RREPI(i, a, b) for (ll i = (ll)a; i >= (ll)b; --i)
#define RREP(...) _overload3(__VA_ARGS__, RREPI, _RREP, )(__VA_ARGS__)
#define EACH(e, v) for (auto &e : v)
#define PERM(v)                                                                \\
  sort(ALL(v));                                                                \\
  for (bool c##p = true; c##p; c##p = next_permutation(ALL(v)))
/* INPUT */
template <typename T> void SSS(T &t) { cin >> t; }
template <typename Head, typename... Tail>
void SSS(Head &&head, Tail &&...tail) {
  cin >> head;
  SSS(tail...);
}
#define SS(T, ...)                                                             \\
  T __VA_ARGS__;                                                               \\
  SSS(__VA_ARGS__);
#define SV(T, v, n)                                                            \\
  vector<T> v(n);                                                              \\
  for (auto &i : v)                                                            \\
    cin >> i;
#define SVV(T, v, n, m)                                                        \\
  vector<vector<T>> v(n, vector<T>(m));                                        \\
  for (auto &r : v)                                                            \\
    for (auto &i : r)                                                          \\
      cin >> i;
/* OUTPUT */
// Yes / No
inline int YES(bool x) {
  cout << (x ? "YES" : "NO") << endl;
  return 0;
}
inline int Yes(bool x) {
  cout << (x ? "Yes" : "No") << endl;
  return 0;
}
inline int yes(bool x) {
  cout << (x ? "yes" : "no") << endl;
  return 0;
}
inline int yES(bool x) {
  cout << (x ? "yES" : "nO") << endl;
  return 0;
}
inline int Yay(bool x) {
  cout << (x ? "Yay!" : ":(") << endl;
  return 0;
}
// PROTOTYPE DECLARATION
template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &j);
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &t);
template <class C, enable_if_t<!is_same<C, string>::value,
                               decltype(declval<const C &>().begin(),
                                        nullptr)> = nullptr>
ostream &operator<<(ostream &os, const C &c);
template <typename T> ostream &operator<<(ostream &os, const stack<T> &j);
template <typename T> ostream &operator<<(ostream &os, const queue<T> &j);
template <typename T, typename C, typename Cmp>
ostream &operator<<(ostream &os, const priority_queue<T, C, Cmp> &j);
// IMPLEMENTATION
template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &j) {
  return os << '{' << j.first << ", " << j.second << '}';
}
template <size_t num = 0, typename... T>
enable_if_t<num == sizeof...(T)> PRINT_TUPLE(ostream &os,
                                             const tuple<T...> &t) {}
template <size_t num = 0, typename... T>
    enable_if_t <
    num<sizeof...(T)> PRINT_TUPLE(ostream &os, const tuple<T...> &t) {
  os << get<num>(t);
  if (num + 1 < sizeof...(T))
    os << ", ";
  PRINT_TUPLE<num + 1>(os, t);
}
template <typename... T>
ostream &operator<<(ostream &os, const tuple<T...> &t) {
  PRINT_TUPLE(os << '{', t);
  return os << '}';
}
template <class C, enable_if_t<!is_same<C, string>::value,
                               decltype(declval<const C &>().begin(), nullptr)>>
ostream &operator<<(ostream &os, const C &c) {
  os << '{';
  for (auto it = begin(c); it != end(c); it++) {
    if (begin(c) != it)
      os << ", ";
    os << *it;
  }
  return os << '}';
}
template <typename T> ostream &operator<<(ostream &os, const stack<T> &j) {
  deque<T> d;
  for (auto c = j; !c.empty(); c.pop())
    d.push_front(c.top());
  return os << d;
}
template <typename T> ostream &operator<<(ostream &os, const queue<T> &j) {
  deque<T> d;
  for (auto c = j; !c.empty(); c.pop())
    d.push_back(c.front());
  return os << d;
}
template <typename T, typename C, typename Cmp>
ostream &operator<<(ostream &os, const priority_queue<T, C, Cmp> &j) {
  deque<T> d;
  for (auto c = j; !c.empty(); c.pop())
    d.push_front(c.top());
  return os << d;
}
// OUTPUT FUNCTION
template <typename T> int PV(T &v) {
  int sz = v.size();
  for (int i = 0; i < sz; ++i)
    cout << v[i] << " \\n"[i == sz - 1];
  return 0;
}
inline int print() {
  cout << endl;
  return 0;
}
template <typename Head> int print(Head &&head) {
  cout << head;
  return print();
}
template <typename Head, typename... Tail>
int print(Head &&head, Tail &&...tail) {
  cout << head << " ";
  return print(forward<Tail>(tail)...);
}
#ifdef LOCAL
inline void dump() { cerr << endl; }
template <typename Head> void dump(Head &&head) {
  cerr << head;
  dump();
}
template <typename Head, typename... Tail>
void dump(Head &&head, Tail &&...tail) {
  cerr << head << ", ";
  dump(forward<Tail>(tail)...);
}
#define debug(...)                                                             \\
  do {                                                                         \\
    cerr << __LINE__ << ":\\t" << #__VA_ARGS__ << " = ";                        \\
    dump(__VA_ARGS__);                                                         \\
  } while (false)
#else
#define dump(...)
#define debug(...)
#endif
/* OTHER */
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define tmax(x, y, z) max((x), max((y), (z)))
#define tmin(x, y, z) min((x), min((y), (z)))
template <typename T, typename A, typename B>
inline bool between(T x, A a, B b) {
  return ((a <= x) && (x < b));
}
template <typename A, typename B> inline bool chmax(A &a, const B &b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename A, typename B> inline bool chmin(A &a, const B &b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
inline ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
inline ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
inline ll POW(ll a, ll b) {
  ll r = 1;
  do {
    if (b & 1)
      r *= a;
    a *= a;
  } while (b >>= 1);
  return r;
}
struct abracadabra {
  abracadabra() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    cerr << fixed << setprecision(5);
  };
} ABRACADABRA;

#pragma endregion

int NN, Q;
int WW[288288];
int VV[288288];

int solve(int n, int max_w, vector<int> &w, vector<int> &v) {
  int g1 = min(12, n);
  int g2 = n - g1;

  map<int, int> mp;
  for (int i = 0; i < (1 << g1); ++i) {
    int wei = 0, val = 0;
    for (int j = 0; j < g1; ++j) {
      if (i & (1 << j)) {
        wei += w[j];
        val += v[j];
        if (wei > max_w)
          break;
      }
    }
    if (wei > max_w)
      continue;
    chmax(mp[wei], val);
  }

  int mx = 0;
  vector<pair<int, int>> vec;
  for (auto &[wei, val] : mp) {
    chmax(mx, val);
    // val = mx;
    vec.emplace_back(-wei, mx);
  }
  reverse(vec.begin(), vec.end());
  // debug(vec);

  int res = 0;

  for (int i = 0; i < (1 << g2); ++i) {
    int wei = 0, val = 0;
    for (int j = 0; j < g2; ++j) {
      if (i & (1 << j)) {
        wei += w[g1 + j];
        val += v[g1 + j];
        if (wei > max_w)
          break;
      }
    }
    if (wei > max_w)
      continue;
    // debug(wei, val, wei - max_w);
    auto itr = lower_bound(vec.begin(), vec.end(), make_pair(wei - max_w, -1));
    if (itr == vec.end())
      continue;
    chmax(res, val + itr->second);
  }

  return res;
}

signed main() {

  cin >> NN;
  REP(i, NN) cin >> VV[i] >> WW[i];

  cin >> Q;
  REP(i, Q) {
    SS(int, v, l);
    int cnt = 0;
    vector<int> pw, pv;
    while (1) {
      ++cnt;
      pw.emplace_back(WW[v - 1]);
      pv.emplace_back(VV[v - 1]);
      v >>= 1;
      if (v == 0)
        break;
    }
    print(solve(cnt, l, pw, pv));
  }
}