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

#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include "bits/stdc++.h"
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

// Begin Header {{{
using namespace std;

#ifndef DEBUG
#define dump(...)
#endif

#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define rep(i, b, e) for (intmax_t i = (b), i##_limit = (e); i < i##_limit; ++i)
#define repc(i, b, e)                                                          \\
  for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)
#define repr(i, b, e)                                                          \\
  for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)
#define var(Type, ...)                                                         \\
  Type __VA_ARGS__;                                                            \\
  input(__VA_ARGS__)

constexpr size_t operator""_zu(unsigned long long value) { return value; };
constexpr intmax_t operator""_jd(unsigned long long value) { return value; };
constexpr uintmax_t operator""_ju(unsigned long long value) { return value; };

constexpr int INF = 0x3f3f3f3f;
constexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;

template <class T, class Compare = less<>>
using MaxHeap = priority_queue<T, vector<T>, Compare>;
template <class T, class Compare = greater<>>
using MinHeap = priority_queue<T, vector<T>, Compare>;

inline void input() {}
template <class Head, class... Tail>
inline void input(Head &&head, Tail &&...tail) {
  cin >> head;
  input(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
          enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline istream &operator>>(istream &is, Container &vs) {
  for (auto &v : vs)
    is >> v;
  return is;
}

inline void output() { cout << "\\n"; }
template <class Head, class... Tail>
inline void output(Head &&head, Tail &&...tail) {
  cout << head;
  if (sizeof...(tail))
    cout << " ";
  output(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
          enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline ostream &operator<<(ostream &os, const Container &vs) {
  static constexpr const char *delim[] = {" ", ""};
  for (auto it = begin(vs); it != end(vs); ++it) {
    os << delim[it == begin(vs)] << *it;
  }
  return os;
}

template <class Iterator>
inline void join(const Iterator &Begin, const Iterator &End,
                 const string &delim = "\\n", const string &last = "\\n") {
  for (auto it = Begin; it != End; ++it) {
    cout << ((it == Begin) ? "" : delim) << *it;
  }
  cout << last;
}

template <class T> inline vector<T> makeVector(const T &initValue, size_t sz) {
  return vector<T>(sz, initValue);
}

template <class T, class... Args>
inline auto makeVector(const T &initValue, size_t sz, Args... args) {
  return vector<decltype(makeVector<T>(initValue, args...))>(
      sz, makeVector<T>(initValue, args...));
}

template <class Func> class FixPoint : Func {
public:
  explicit constexpr FixPoint(Func &&f) noexcept : Func(forward<Func>(f)) {}

  template <class... Args>
  constexpr decltype(auto) operator()(Args &&...args) const {
    return Func::operator()(*this, std::forward<Args>(args)...);
  }
};

template <class Func>
static inline constexpr decltype(auto) makeFixPoint(Func &&f) noexcept {
  return FixPoint<Func>{forward<Func>(f)};
}

template <class Container> struct reverse_t {
  Container &c;
  reverse_t(Container &c) : c(c) {}
  auto begin() { return c.rbegin(); }
  auto end() { return c.rend(); }
};

template <class Container> auto reversed(Container &c) {
  return reverse_t<Container>(c);
}

template <class T> inline bool chmax(T &a, const T &b) noexcept {
  return b > a && (a = b, true);
}

template <class T> inline bool chmin(T &a, const T &b) noexcept {
  return b < a && (a = b, true);
}

template <class T> inline T diff(const T &a, const T &b) noexcept {
  return a < b ? b - a : a - b;
}

void ioinit() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << fixed << setprecision(10);
  clog << fixed << setprecision(10);
}
// }}} End Header

// Mo's algorithm {{{
template <class T> T isqrt(T n) {
  if (n <= 1)
    return n;
  T ok = 1;
  T ng = static_cast<T>(1) << (CHAR_BIT * (sizeof(T) / 2));
  while (ng - ok > 1) {
    const T mid = (ok + ng) >> 1;
    if (mid * mid <= n)
      ok = mid;
    else
      ng = mid;
  }
  return ok;
}

struct Mo {
  size_t wid;
  vector<size_t> ls, rs, is;
  vector<bool> vs;

  Mo(size_t N, size_t Q) : wid(isqrt(N)), is(Q), vs(N) {
    iota(is.begin(), is.end(), 0);
  }

  // [l, r)
  void insert(size_t l, size_t r) {
    ls.emplace_back(l);
    rs.emplace_back(r);
  }

  template <typename Add, typename Remove, typename Result>
  void exec(const Add &addFunc, const Remove &removeFunc,
            const Result &resultFunc) {
    assert(ls.size() == rs.size());
    sort(is.begin(), is.end(), [&](size_t i0, size_t i1) {
      const size_t l0 = ls[i0] / wid;
      const size_t r0 = rs[i0];
      const size_t l1 = ls[i1] / wid;
      const size_t r1 = rs[i1];
      if (l0 != l1)
        return l0 < l1;
      if (l0 & 1)
        return r0 < r1;
      return r0 > r1;
    });
    const auto func = [&](size_t i) -> void {
      vs[i].flip();
      if (vs[i])
        addFunc(i);
      else
        removeFunc(i);
    };
    size_t l = 0, r = 0;
    for (const auto i : is) {
      while (ls[i] < l)
        func(--l);
      while (r < rs[i])
        func(r++);
      while (l < ls[i])
        func(l++);
      while (rs[i] < r)
        func(--r);
      resultFunc(i);
    }
  }
};
// }}}

signed main() {
  ioinit();

  var(size_t, N, Q);

  vector<size_t> c(N);
  for (auto &ci : c)
    cin >> ci, ci--;

  Mo mo(N, Q);
  rep(_, 0, Q) {
    var(size_t, l, r);
    mo.insert(l - 1, r);
  }

  vector<size_t> cnt(N), res(Q);
  size_t sum = 0;
  const auto addFunc = [&](size_t i) {
    if (cnt[c[i]] == 0)
      sum++;
    cnt[c[i]]++;
  };
  const auto removeFunc = [&](size_t i) {
    cnt[c[i]]--;
    if (cnt[c[i]] == 0)
      sum--;
  };
  const auto resultFunc = [&](size_t i) { res[i] = sum; };
  mo.exec(addFunc, removeFunc, resultFunc);

  join(all(res));
  return 0;
}


Error: TLE

Fixed submission:

#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include "bits/stdc++.h"
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

// Begin Header {{{
using namespace std;

#ifndef DEBUG
#define dump(...)
#endif

#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define rep(i, b, e) for (intmax_t i = (b), i##_limit = (e); i < i##_limit; ++i)
#define repc(i, b, e)                                                          \\
  for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)
#define repr(i, b, e)                                                          \\
  for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)
#define var(Type, ...)                                                         \\
  Type __VA_ARGS__;                                                            \\
  input(__VA_ARGS__)

constexpr size_t operator""_zu(unsigned long long value) { return value; };
constexpr intmax_t operator""_jd(unsigned long long value) { return value; };
constexpr uintmax_t operator""_ju(unsigned long long value) { return value; };

constexpr int INF = 0x3f3f3f3f;
constexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;

template <class T, class Compare = less<>>
using MaxHeap = priority_queue<T, vector<T>, Compare>;
template <class T, class Compare = greater<>>
using MinHeap = priority_queue<T, vector<T>, Compare>;

inline void input() {}
template <class Head, class... Tail>
inline void input(Head &&head, Tail &&...tail) {
  cin >> head;
  input(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
          enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline istream &operator>>(istream &is, Container &vs) {
  for (auto &v : vs)
    is >> v;
  return is;
}

inline void output() { cout << "\\n"; }
template <class Head, class... Tail>
inline void output(Head &&head, Tail &&...tail) {
  cout << head;
  if (sizeof...(tail))
    cout << " ";
  output(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
          enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline ostream &operator<<(ostream &os, const Container &vs) {
  static constexpr const char *delim[] = {" ", ""};
  for (auto it = begin(vs); it != end(vs); ++it) {
    os << delim[it == begin(vs)] << *it;
  }
  return os;
}

template <class Iterator>
inline void join(const Iterator &Begin, const Iterator &End,
                 const string &delim = "\\n", const string &last = "\\n") {
  for (auto it = Begin; it != End; ++it) {
    cout << ((it == Begin) ? "" : delim) << *it;
  }
  cout << last;
}

template <class T> inline vector<T> makeVector(const T &initValue, size_t sz) {
  return vector<T>(sz, initValue);
}

template <class T, class... Args>
inline auto makeVector(const T &initValue, size_t sz, Args... args) {
  return vector<decltype(makeVector<T>(initValue, args...))>(
      sz, makeVector<T>(initValue, args...));
}

template <class Func> class FixPoint : Func {
public:
  explicit constexpr FixPoint(Func &&f) noexcept : Func(forward<Func>(f)) {}

  template <class... Args>
  constexpr decltype(auto) operator()(Args &&...args) const {
    return Func::operator()(*this, std::forward<Args>(args)...);
  }
};

template <class Func>
static inline constexpr decltype(auto) makeFixPoint(Func &&f) noexcept {
  return FixPoint<Func>{forward<Func>(f)};
}

template <class Container> struct reverse_t {
  Container &c;
  reverse_t(Container &c) : c(c) {}
  auto begin() { return c.rbegin(); }
  auto end() { return c.rend(); }
};

template <class Container> auto reversed(Container &c) {
  return reverse_t<Container>(c);
}

template <class T> inline bool chmax(T &a, const T &b) noexcept {
  return b > a && (a = b, true);
}

template <class T> inline bool chmin(T &a, const T &b) noexcept {
  return b < a && (a = b, true);
}

template <class T> inline T diff(const T &a, const T &b) noexcept {
  return a < b ? b - a : a - b;
}

void ioinit() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << fixed << setprecision(10);
  clog << fixed << setprecision(10);
}
// }}} End Header

// Mo's algorithm {{{
template <class T> T isqrt(T n) {
  if (n <= 1)
    return n;
  T ok = 1;
  T ng = static_cast<T>(1) << (CHAR_BIT * (sizeof(T) / 2));
  while (ng - ok > 1) {
    const T mid = (ok + ng) >> 1;
    if (mid * mid <= n)
      ok = mid;
    else
      ng = mid;
  }
  return ok;
}

struct Mo {
  size_t wid;
  vector<size_t> ls, rs, is;
  vector<bool> vs;

  Mo(size_t N, size_t Q) : wid(isqrt(N)), is(Q), vs(N) {
    iota(is.begin(), is.end(), 0);
  }

  // [l, r)
  void insert(size_t l, size_t r) {
    ls.emplace_back(l);
    rs.emplace_back(r);
  }

  template <typename Add, typename Remove, typename Result>
  void exec(const Add &addFunc, const Remove &removeFunc,
            const Result &resultFunc) {
    assert(ls.size() == rs.size());
    sort(is.begin(), is.end(), [&](size_t i0, size_t i1) {
      const size_t l0 = ls[i0] / wid;
      const size_t r0 = rs[i0];
      const size_t l1 = ls[i1] / wid;
      const size_t r1 = rs[i1];
      if (l0 != l1)
        return l0 < l1;
      if (r0 != r1)
        return r0 < r1;
      return false;
    });
    const auto func = [&](size_t i) -> void {
      vs[i].flip();
      if (vs[i])
        addFunc(i);
      else
        removeFunc(i);
    };
    size_t l = 0, r = 0;
    for (const auto i : is) {
      while (ls[i] < l)
        func(--l);
      while (r < rs[i])
        func(r++);
      while (l < ls[i])
        func(l++);
      while (rs[i] < r)
        func(--r);
      resultFunc(i);
    }
  }
};
// }}}

signed main() {
  ioinit();

  var(size_t, N, Q);

  vector<size_t> c(N);
  for (auto &ci : c)
    cin >> ci, ci--;

  Mo mo(N, Q);
  rep(_, 0, Q) {
    var(size_t, l, r);
    mo.insert(l - 1, r);
  }

  vector<size_t> cnt(N), res(Q);
  size_t sum = 0;
  const auto addFunc = [&](size_t i) {
    if (cnt[c[i]] == 0)
      sum++;
    cnt[c[i]]++;
  };
  const auto removeFunc = [&](size_t i) {
    cnt[c[i]]--;
    if (cnt[c[i]] == 0)
      sum--;
  };
  const auto resultFunc = [&](size_t i) { res[i] = sum; };
  mo.exec(addFunc, removeFunc, resultFunc);

  join(all(res));
  return 0;
}