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

#define _CRT_SECURE_NO_WARNINGS
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// #define int ll
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pii;
#define all(c) begin(c), end(c)
#define range(i, a, b) for (ll i = a; i < ll(b); i++)
#define rep(i, b) range(i, 0, b)
#define rangei(i, a, b) for (ll a = a; i <= ll(b); i++)
#define repi(i, b) rangei(i, 1, b)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
template <class T> ostream &operator<<(ostream &os, vector<T> const &);
template <int n, class... T>
typename enable_if<(n >= sizeof...(T))>::type _ot(ostream &,
                                                  tuple<T...> const &) {}
template <int n, class... T>
typename enable_if<(n < sizeof...(T))>::type _ot(ostream &os,
                                                 tuple<T...> const &t) {
  os << (n == 0 ? "" : " ") << get<n>(t);
  _ot<n + 1>(os, t);
}
template <class... T> ostream &operator<<(ostream &os, tuple<T...> const &t) {
  _ot<0>(os, t);
  return os;
}
template <class T, class U>
ostream &operator<<(ostream &os, pair<T, U> const &p) {
  return os << "(" << p.first << ", " << p.second << ") ";
}
template <class T> ostream &operator<<(ostream &os, vector<T> const &v) {
  rep(i, v.size()) os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
  return os;
}
#ifdef DEBUG
#define dump(...)                                                              \\
  (cerr << #__VA_ARGS__ << " = " << mt(__VA_ARGS__) << " [" << __LINE__ << "]" \\
        << endl)
#else
#define dump(...)
#endif
void fastios() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  // #define endl '\\n'
}
template <class T> size_t uniq(vector<T> &v) {
  sort(v.begin(), v.end());
  v.erase(unique(v.begin(), v.end()), v.end());
  return v.size();
}
template <class T> size_t uniq(T *l, size_t n) {
  sort(l, l + n);
  return unique(l, l + n) - l;
}
#define mems(arr, val) memset(arr, val, sizeof(arr));
int const mod = 1000000007;
int const inf = numeric_limits<int>::max() / 8;

struct Timer {
  clock_t p;
  Timer() { reset(); }
  void reset() { p = clock(); }
  double get() { return (double)(clock() - p) / CLOCKS_PER_SEC; }
};

struct HeavyLightDecomposition {
  int size;
  vector<vector<int>> g;
  vector<int> parent, subtreeSize, depth;
  vector<int> head, last, next, prev;
  vector<int> chain, at;
  vector<vector<int>> chains;

  template <class Graph> HeavyLightDecomposition(const Graph &g_) {
    size = g_.size();
    g.resize(size);
    vector<int64_t> es;
    for (size_t i = 0; i < g_.size(); i++) {
      for (auto &e : g_[i]) {
        int a = e.src, b = e.dst;
        if (a > b)
          swap(a, b);
        es.eb((int64_t)a << 32 | b);
      }
    }
    sort(es.begin(), es.end());
    es.erase(unique(es.begin(), es.end()), es.end());
    for (int64_t &e : es) {
      addEdge(e >> 32, e & 0xFFFFFFFF);
    }
  }

  HeavyLightDecomposition(int n_) : size(n_), g(n_) {}

  void addEdge(int a, int b) {
    g[a].push_back(b);
    g[b].push_back(a);
  }

  int goUp(int &v) const { return parent[head[v]]; }

  void decompose(const int root = 0) {
    parent.assign(size, 0);
    subtreeSize.assign(size, 0);
    depth.assign(size, -1);
    head.assign(size, 0);
    last.assign(size, 0);
    next.assign(size, -1);
    prev.assign(size, -1);
    chain.assign(size, -1);
    at.assign(size, 0);
    static int stk[600010], k = 0;
    stk[k++] = root;
    parent[root] = -1;
    depth[root] = 0;
    while (k) {
      const int v = stk[--k];
      if (v >= 0) {
        stk[k++] = ~v;
        for (const int ch : g[v]) {
          if (depth[ch] != -1)
            continue;
          depth[ch] = depth[v] + 1;
          parent[ch] = v;
          stk[k++] = ch;
        }
      } else {
        const int u = ~v;
        subtreeSize[u] = 1;
        int m = 0;
        for (const int ch : g[u]) {
          if (parent[u] == ch)
            continue;
          subtreeSize[u] += subtreeSize[ch];
          if (m < subtreeSize[ch]) {
            m = subtreeSize[ch];
            next[u] = ch;
          }
        }
      }
    }

    k = 0;
    stk[k++] = root;
    while (k) {
      const int head_ = stk[--k];
      for (const int ch : g[head_]) {
        if (parent[head_] == ch)
          continue;
        stk[k++] = ch;
      }
      if (chain[head_] != -1)
        continue;
      chains.push_back(vector<int>());
      vector<int> &path = chains.back();
      int cur = head_;
      while (cur != -1) {
        path.push_back(cur);
        cur = next[cur];
      }
      for (size_t i = 0; i < path.size(); i++) {
        const int v = path[i];
        head[v] = path.front();
        last[v] = path.back();
        next[v] = i + 1 != path.size() ? path[i + 1] : -1;
        prev[v] = i != 0 ? path[i - 1] : -1;
        chain[v] = chains.size() - 1;
        at[v] = i;
      }
    }
  }

  int lca(int u, int v) {
    while (chain[u] != chain[v]) {
      if (depth[head[u]] > depth[head[v]])
        u = goUp(u);
      else
        v = goUp(v);
    }
    return depth[u] < depth[v] ? u : v;
  }

  vector<set<pair<int, int>>> marks; // -depth, node
  void prepare() { marks.assign(chains.size(), {}); }
  void mark(int v) { marks[chain[v]].insert(mp(-depth[v], v)); }
  int query(int v) {
    vector<int> hist;
    int res = -1;
    Timer t;
    while (v != -1) {
      auto ms = marks[chain[v]];
      auto it = ms.lower_bound(make_pair(-depth[v], -inf));
      // dump(ms.size());
      if (it != ms.end()) {
        res = it->second;
        break;
      } else {
        v = goUp(v);
      }
    }
    // dump(t.get());
    assert(res != -1);
    return res;
  }
};

typedef int Weight;
struct Edge {
  int src, dst;
  Edge(int src_, int dst_) : src(src_), dst(dst_) {}
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

int n, q;
Graph g;
char qt[100010];
int qv[100010];

ll solve() {
  ll ans = 0;
  HeavyLightDecomposition h(g);
  h.decompose();
  if (h.chains.size() == 1) {
    // なぜか構造体の中でやると激重
    set<pair<int, int>> marks;
    marks.insert(make_pair(0, 0));
    rep(i, q) {
      int d = h.depth[qv[i]];
      if (qt[i] == 'Q') {
        ans += marks.lower_bound(make_pair(-d, -inf))->second + 1;
      } else {
        marks.insert(mp(-d, qv[i]));
      }
    }
  } else {
    h.prepare();
    h.mark(0);
    double Qt = 0, Mt = 0;
    rep(i, q) {
      if (qt[i] == 'Q') {
        Timer t;
        ans += h.query(qv[i]) + 1;
        Qt += t.get();
      } else {
        Timer t;
        h.mark(qv[i]);
        Mt += t.get();
      }
    }
  }
  return ans;
}

int main() {
  fastios();
  while (cin >> n >> q && n) {
    g.assign(n, {});
    rep(i, n - 1) {
      int par;
      cin >> par;
      par--;
      g[par].eb(par, i + 1);
      g[i + 1].eb(i + 1, par);
    }
    rep(i, q) {
      cin >> qt[i] >> qv[i];
      qv[i]--;
    }
    cout << solve() << endl;
  }
}

Error: TLE

Fixed submission:

#define _CRT_SECURE_NO_WARNINGS
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// #define int ll
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pii;
#define all(c) begin(c), end(c)
#define range(i, a, b) for (ll i = a; i < ll(b); i++)
#define rep(i, b) range(i, 0, b)
#define rangei(i, a, b) for (ll a = a; i <= ll(b); i++)
#define repi(i, b) rangei(i, 1, b)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
template <class T> ostream &operator<<(ostream &os, vector<T> const &);
template <int n, class... T>
typename enable_if<(n >= sizeof...(T))>::type _ot(ostream &,
                                                  tuple<T...> const &) {}
template <int n, class... T>
typename enable_if<(n < sizeof...(T))>::type _ot(ostream &os,
                                                 tuple<T...> const &t) {
  os << (n == 0 ? "" : " ") << get<n>(t);
  _ot<n + 1>(os, t);
}
template <class... T> ostream &operator<<(ostream &os, tuple<T...> const &t) {
  _ot<0>(os, t);
  return os;
}
template <class T, class U>
ostream &operator<<(ostream &os, pair<T, U> const &p) {
  return os << "(" << p.first << ", " << p.second << ") ";
}
template <class T> ostream &operator<<(ostream &os, vector<T> const &v) {
  rep(i, v.size()) os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
  return os;
}
#ifdef DEBUG
#define dump(...)                                                              \\
  (cerr << #__VA_ARGS__ << " = " << mt(__VA_ARGS__) << " [" << __LINE__ << "]" \\
        << endl)
#else
#define dump(...)
#endif
void fastios() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  // #define endl '\\n'
}
template <class T> size_t uniq(vector<T> &v) {
  sort(v.begin(), v.end());
  v.erase(unique(v.begin(), v.end()), v.end());
  return v.size();
}
template <class T> size_t uniq(T *l, size_t n) {
  sort(l, l + n);
  return unique(l, l + n) - l;
}
#define mems(arr, val) memset(arr, val, sizeof(arr));
int const mod = 1000000007;
int const inf = numeric_limits<int>::max() / 8;

struct HeavyLightDecomposition {
  int size;
  vector<vector<int>> g;
  vector<int> parent, subtreeSize, depth;
  vector<int> head, last, next, prev;
  vector<int> chain, at;
  vector<vector<int>> chains;

  template <class Graph> HeavyLightDecomposition(const Graph &g_) {
    size = g_.size();
    g.resize(size);
    vector<int64_t> es;
    for (size_t i = 0; i < g_.size(); i++) {
      for (auto &e : g_[i]) {
        int a = e.src, b = e.dst;
        if (a > b)
          swap(a, b);
        es.eb((int64_t)a << 32 | b);
      }
    }
    sort(es.begin(), es.end());
    es.erase(unique(es.begin(), es.end()), es.end());
    for (auto &e : es)
      addEdge(e >> 32, e & 0xFFFFFFFF);
  }

  HeavyLightDecomposition(int n_) : size(n_), g(n_) {}

  void addEdge(int a, int b) {
    g[a].push_back(b);
    g[b].push_back(a);
  }

  int goUp(int &v) const { return parent[head[v]]; }

  void decompose(const int root = 0) {
    parent.assign(size, 0);
    subtreeSize.assign(size, 0);
    depth.assign(size, -1);
    head.assign(size, 0);
    last.assign(size, 0);
    next.assign(size, -1);
    prev.assign(size, -1);
    chain.assign(size, -1);
    at.assign(size, 0);
    static int stk[600010], k = 0;
    stk[k++] = root;
    parent[root] = -1;
    depth[root] = 0;
    while (k) {
      const int v = stk[--k];
      if (v >= 0) {
        stk[k++] = ~v;
        for (const int ch : g[v]) {
          if (depth[ch] != -1)
            continue;
          depth[ch] = depth[v] + 1;
          parent[ch] = v;
          stk[k++] = ch;
        }
      } else {
        const int u = ~v;
        subtreeSize[u] = 1;
        int m = 0;
        for (const int ch : g[u]) {
          if (parent[u] == ch)
            continue;
          subtreeSize[u] += subtreeSize[ch];
          if (m < subtreeSize[ch]) {
            m = subtreeSize[ch];
            next[u] = ch;
          }
        }
      }
    }

    k = 0;
    stk[k++] = root;
    while (k) {
      const int head_ = stk[--k];
      for (const int ch : g[head_]) {
        if (parent[head_] == ch)
          continue;
        stk[k++] = ch;
      }
      if (chain[head_] != -1)
        continue;
      chains.push_back(vector<int>());
      vector<int> &path = chains.back();
      int cur = head_;
      while (cur != -1) {
        path.push_back(cur);
        cur = next[cur];
      }
      for (size_t i = 0; i < path.size(); i++) {
        const int v = path[i];
        head[v] = path.front();
        last[v] = path.back();
        next[v] = i + 1 != path.size() ? path[i + 1] : -1;
        prev[v] = i != 0 ? path[i - 1] : -1;
        chain[v] = chains.size() - 1;
        at[v] = i;
      }
    }
  }

  int lca(int u, int v) {
    while (chain[u] != chain[v]) {
      if (depth[head[u]] > depth[head[v]])
        u = goUp(u);
      else
        v = goUp(v);
    }
    return depth[u] < depth[v] ? u : v;
  }

  vector<map<int, int>> marks; // -depth, node
  void prepare() { marks.assign(chains.size(), {}); }
  void mark(int v) { marks[chain[v]].insert(mp(-depth[v], v)); }
  int query(int v) {
    while (1) {
      dump(v);
      auto ms = marks[chain[v]];
      auto it = ms.lower_bound(v);
      for (auto &m : ms) {
        dump(m);
      }
      if (it != ms.end()) {
        dump(*it);
        return it->second;
      } else {
        v = goUp(v);
      }
    }
    assert(false);
  }
};

typedef int Weight;
struct Edge {
  int src, dst;
  Edge(int src_, int dst_) : src(src_), dst(dst_) {}
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

int n, q;
Graph g;
char qt[100010];
int qv[100010];

int solve() {
  int ans = 0;
  HeavyLightDecomposition h(g);
  h.decompose();
  h.prepare();
  h.mark(0);
  rep(i, q) {
    if (qt[i] == 'Q') {
      ans += h.query(qv[i]) + 1;
    } else {
      h.mark(qv[i]);
    }
  }
  return ans;
}

int main() {
  fastios();
  while (cin >> n >> q && n) {
    g.assign(n, {});
    rep(i, n - 1) {
      int par;
      cin >> par;
      par--;
      g[i + 1].eb(i + 1, par);
    }
    rep(i, q) {
      cin >> qt[i] >> qv[i];
      qv[i]--;
    }
    cout << solve() << endl;
  }
}