Source Code
#define ll long long
#define fr first
#define sc second
#define pb(x) push_back(x)
#define nxt continue
#define sz(container) ((ll) container.size())
#define umap unordered_map
#define uset unordered_set
#define MAX LONG_LONG_MAX
#define MIN LONG_LONG_MIN
#define mkpr(f, s) make_pair(f, s)
#define el '\n'
#define mpq(T) priority_queue<(T), vector<(T)>, greater<(T)>>
#define pq priority_queue

#include <bits/stdc++.h>
using namespace std;

const ll MOD = 1e9;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  
  ll t, n, i;
  
  cin >> t;
  
  while (t--) {
    cin >> n;
    
    vector<ll> v(n);
    
    for (ll& e : v)
      cin >> e;
      
    for (i = 0; i < n; ++i) {
      if (v[i] == 0)
        break;
    }
    
    ll ans = 0;
    
    for (ll j = i; j < n; ++j) {
      set<ll> st;
      
      for (ll k = i + 1; k <= j; ++k)
        st.insert(v[k]);
      
      ll mex = 1;
      
      for (ll k = i; k > -1; --k) {
        st.insert(v[k]);
        
        auto it = st.find(mex);
        
        while (it != st.end()) {
          if (*it != mex)
            break;
          ++mex;
          ++it;
        }
        
        ans += mex;
      }
    }
    
    cout << ans << el;
  }
  
  return 0;
}
Copy
Mex Nedal
GNU G++17
2054 ms
336 KB
Time Limit Exceeded