#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; template vector> vec2d(int n, int m, T v){ return vector>(n, vector(m, v)); } template vector>> vec3d(int n, int m, int k, T v){ return vector>>(n, vector>(m, vector(k, v))); } template void print_vector(vector v, char delimiter=' '){ if(v.empty()) { cout << endl; return; } for(int i = 0; i+1 < v.size(); i++) cout << v[i] << delimiter; cout << v.back() << endl; } //1-indexed template struct bit{ int n; vector data; bit(int n_){ n = 1; while(n < n_) n *= 2; data = vector(n+1); for(int i = 0; i <= n; i++) data[i] = 0; } T sum(int i){ T ret = 0; while(i > 0){ ret += data[i]; i -= i&-i; } return ret; } void add(int i, T x){ while(i <= n){ data[i] += x; i += i&-i; } } }; const int N = 100000; int a[N]; vector indices[N]; int count(int x, int l, int r){ return lower_bound(indices[x].begin(), indices[x].end(), r) - lower_bound(indices[x].begin(), indices[x].end(), l); } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n; cin >> n; for(int i = 0; i < n; i++){ int x; cin >> x; x--; a[i] = x; indices[x].push_back(i); } ll ans = 0; int th = 100; for(int x = 0; x < N; x++){ if(indices[x].size() < th) continue; bit bt(2*n+1); int sum = n+1; bt.add(sum, 1); for(int i = 0; i < n; i++){ if(a[i] == x) sum++; else sum--; ans += bt.sum(sum-1); bt.add(sum, 1); } } for(int l = 0; l < n; l++){ int r = l; int cnt = 0; int candidate = -1; while(r < l+th*2+10 && r < n){ if(cnt == 0) candidate = a[r]; if(a[r] == candidate) cnt++; else cnt--; r++; if(indices[candidate].size() < th) { int len = r-l; if(count(candidate, l, r)*2 > len) ans++; } } } cout << ans << endl; }