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

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class c, class cmp = less<c>>
using ordered_set =
    tree<c, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
#define IOS                                                                    \\
  ios_base::sync_with_stdio(false);                                            \\
  cin.tie(NULL);                                                               \\
  cout.tie(NULL);
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1> void __f(const char *name, Arg1 &&arg1) {
  cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
  const char *comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
#else
#define trace(...)
#endif
template <class T> ostream &operator<<(ostream &os, vector<T> V) {
  os << "[ ";
  for (auto v : V)
    os << v << " ";
  return os << "]";
}
template <class L, class R> ostream &operator<<(ostream &os, pair<L, R> P) {
  return os << "(" << P.first << "," << P.second << ")";
}
template <typename T, typename U>
pair<T, U> operator+(const pair<T, U> &l, const std::pair<T, U> &r) {
  return {l.first + r.first, l.second + r.second};
}
typedef long long int ll;
const ll mod = 1e9 + 7;
const int maxn = 500005;
#define endl '\\n'
#define ld long double
// #define int ll
#define all(x) (x).begin(), (x).end()
#define ff first
#define ss second
#define pll pair<int, int>
#define mp make_pair
#define pb push_back
const int MAX = 1000001;

// structure to store queries
struct Query {
  int l, r, idx;
};

// cmp function to sort queries according to r
bool cmp(Query x, Query y) { return x.r < y.r; }

// updating the bit array
void update(int idx, int val, int bit[], int n) {
  for (; idx <= n; idx += idx & -idx)
    bit[idx] += val;
}

// querying the bit array
int query(int idx, int bit[], int n) {
  int sum = 0;
  for (; idx > 0; idx -= idx & -idx)
    sum += bit[idx];
  return sum;
}

void answeringQueries(int arr[], int n, Query queries[], int q) {
  // initialising bit array
  int bit[n + 1];
  memset(bit, 0, sizeof(bit));

  // holds the rightmost index of any number
  // as numbers of a[i] are less than or equal to 10^6
  int last_visit[MAX];
  memset(last_visit, -1, sizeof(last_visit));

  // answer for each query
  int ans[q];
  int query_counter = 0;
  for (int i = 0; i < n; i++) {
    // If last visit is not -1 update -1 at the
    // idx equal to last_visit[arr[i]]
    if (last_visit[arr[i]] != -1)
      update(last_visit[arr[i]] + 1, -1, bit, n);

    // Setting last_visit[arr[i]] as i and updating
    // the bit array accordingly
    last_visit[arr[i]] = i;
    update(i + 1, 1, bit, n);

    // If i is equal to r of any query  store answer
    // for that query in ans[]
    while (query_counter < q && queries[query_counter].r == i) {
      ans[queries[query_counter].idx] =
          query(queries[query_counter].r + 1, bit, n) -
          query(queries[query_counter].l, bit, n);
      query_counter++;
    }
  }

  // print answer for each query
  for (int i = 0; i < q; i++)
    cout << ans[i] << endl;
}

int32_t main() {
  IOS

      // driver code

      int n,
      q;
  cin >> n >> q;
  int a[n];
  for (int i = 0; i < n; i++)
    cin >> a[i];
  Query queries[q];
  for (int i = 0; i < q; i++) {
    cin >> queries[i].l >> queries[i].r;
    queries[i].l--;
    queries[i].r--;
    queries[i].idx = i;
  }
  sort(queries, queries + q, cmp);
  answeringQueries(a, n, queries, q);
  return 0;
}

Error: TLE

Fixed submission:

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class c, class cmp = less<c>>
using ordered_set =
    tree<c, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
#define IOS                                                                    \\
  ios_base::sync_with_stdio(false);                                            \\
  cin.tie(NULL);                                                               \\
  cout.tie(NULL);
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1> void __f(const char *name, Arg1 &&arg1) {
  cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
  const char *comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
#else
#define trace(...)
#endif
template <class T> ostream &operator<<(ostream &os, vector<T> V) {
  os << "[ ";
  for (auto v : V)
    os << v << " ";
  return os << "]";
}
template <class L, class R> ostream &operator<<(ostream &os, pair<L, R> P) {
  return os << "(" << P.first << "," << P.second << ")";
}
template <typename T, typename U>
pair<T, U> operator+(const pair<T, U> &l, const std::pair<T, U> &r) {
  return {l.first + r.first, l.second + r.second};
}
typedef long long int ll;
const ll mod = 1e9 + 7;
const int maxn = 500005;
#define endl '\\n'
#define ld long double
// #define int ll
#define all(x) (x).begin(), (x).end()
#define ff first
#define ss second
#define pll pair<int, int>
#define mp make_pair
#define pb push_back
ll BLOCK = 700;

bool comp(pair<pll, ll> a, pair<pll, ll> b) {
  if (a.ff.ff / BLOCK != b.ff.ff / BLOCK)
    return (a.ff.ff / BLOCK < b.ff.ff / BLOCK);
  else {
    return a.ff.ss < b.ff.ss;
  }
}
int a[maxn], cnt[maxn], answer = 0;
void add(int position) {
  cnt[a[position]]++;
  if (cnt[a[position]] == 1) {
    answer++;
  }
}

void remove(int position) {
  cnt[a[position]]--;
  if (cnt[a[position]] == 0) {
    answer--;
  }
}
int32_t main() {
  IOS
#ifndef ONLINE_JUDGE
      freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
#endif
  int n;
  cin >> n;
  int q;
  cin >> q;
  for (int i = 1; i <= n; i++)
    cin >> a[i];
  BLOCK = (int)(sqrt(n));
  int ans[q];
  vector<pair<pll, ll>> queries;
  for (int qq = 0; qq < q; qq++) {
    int l, r;
    cin >> l >> r;
    queries.pb(mp(mp(l, r), qq));
  }
  sort(queries.begin(), queries.end(), comp);
  int currentL = 0, currentR = 0;
  for (int i = 0; i < q; i++) {
    while (currentL < queries[i].ff.ff) {
      remove(currentL);
      currentL++;
    }
    while (currentL > queries[i].ff.ff) {
      add(currentL - 1);
      currentL--;
    }
    while (currentR < queries[i].ff.ss) {
      add(currentR + 1);
      currentR++;
    }
    while (currentR > queries[i].ff.ss) {
      remove(currentR);
      currentR--;
    }
    ans[queries[i].ss] = answer;
  }
  for (int i = 0; i < q; i++) {
    cout << ans[i] << endl;
  }
}