#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define endl "\n"
using namespace std;
using namespace __gnu_pbds;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T, typename key = less_equal<T>>
using ordered_set = tree<T, null_type, key, rb_tree_tag, tree_order_statistics_node_update>;
const ll N = 2e5 + 5, B = 450, offset = 2e5 + 1;
ll t[N * 2], cnt[N], pref[N];
ll sum(ll i)
{
ll res = 0;
for (; i >= 0; i = (i & (i + 1)) - 1)
res += t[i];
return res;
}
void upd(ll i, ll d)
{
for (; i < N * 2; i = (i | (i + 1)))
t[i] += d;
}
void solve()
{
ll n;
cin >> n;
ll a[n + 1];
vector<ll> freq[n + 1];
for (ll i = 1; i <= n; i++)
cin >> a[i];
{
ll b[n];
for (ll i = 1; i <= n; i++)
b[i - 1] = a[i];
sort(b, b + n);
for (ll i = 1; i <= n; i++)
a[i] = lower_bound(b, b + n, a[i]) - b + 1;
}
// for (ll i = 1; i <= n; i++) cout << a[i] << " ";
for (ll i = 1; i <= n; i++)
freq[a[i]].push_back(i);
multiset<ll> s;
ll ans = 0;
for (ll x = 1; x <= min(B, n); x++)
{
for (ll i = 1; i <= n; i++)
cnt[i] = 0;
s.clear();
for (ll i = 1; i <= x; i++)
cnt[a[i]]++;
for (ll i = 1; i <= n; i++)
s.insert(cnt[i]);
if (*s.rbegin() > x / 2)
ans++;
for (ll i = x + 1; i <= n; i++)
{
if (a[i] != a[i - x])
{
s.erase(s.find(cnt[a[i - x]]));
s.erase(s.find(cnt[a[i]]));
cnt[a[i - x]]--;
cnt[a[i]]++;
s.insert(cnt[a[i - x]]);
s.insert(cnt[a[i]]);
}
if (*s.rbegin() > x / 2)
ans++;
}
}
for (ll x = 1; x <= n; x++)
if (freq[x].size() * 2 > B)
{
pref[0] = 0;
for (ll i = 1; i <= n; i++)
pref[i] = pref[i - 1] + (a[i] == x ? 1 : -1);
for (ll i = 0; i <= n * 2 + 5; i++)
t[i] = 0;
for (ll i = B + 1; i <= n; i++)
{
upd(pref[i - B - 1] + offset, 1);
ans += sum(pref[i] + offset - 1);
}
}
cout << ans << endl;
}
int main()
{
// ios_base::sync_with_stdio(0);
// cin.tie(0);
ll t = 1;
// precomp();
// cin >> t;
for (ll cs = 1; cs <= t; cs++)
solve();
// cerr << "\nTime elapsed: " << clock() * 1000.0 / CLOCKS_PER_SEC << " ms\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |