#include<iostream> #include<cstdio> #define maxn 500010 #define INF 1000000000000000000 #define ll long long usingnamespacestd;
int n, k, a[maxn];
int cnt[maxn], l, r; ll sum; inlinevoidadd(int x){ sum += cnt[x]++; } inlinevoiddel(int x){ sum -= --cnt[x]; } voidmove(int L, int R){ while (r < R) add(a[++r]); while (l > L) add(a[--l]); while (r > R) del(a[r--]); while (l < L) del(a[l++]); }
ll f[maxn], g[maxn]; voidsolve(int l, int r, int L, int R){ // f_i in [l, r], g_j in [L, R] if (l > r) return ; int m = l + r >> 1, p = L; for (int i = L; i <= min(R, m - 1); ++i) { move(i + 1, m); if (g[i] + sum < f[m]) f[m] = g[i] + sum, p = i; } solve(l, m - 1, L, p); solve(m + 1, r, p, R); }