1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <iostream> #include <cstdio> #include <stack> #define maxn 300010 #define ll long long using namespace std;
int n, m, a[maxn], mx[maxn], mn[maxn];
#define lc i << 1 #define rc i << 1 | 1 struct Seg { int f0, v; } T[maxn * 4]; inline void maintain(int i) { T[i].v = T[lc].v + T[rc].v; }
void build(int i, int l, int r) { T[i].v = r - l + 1; T[i].f0 = 0; if (l == r) return ; int m = l + r >> 1; build(lc, l, m); build(rc, m + 1, r); }
inline void Up(int i) { T[i].f0 = 1; T[i].v = 0; }
inline void pushdown(int i) { int &f0 = T[i].f0; if (!f0) return ; Up(lc); Up(rc); }
void update(int i, int l, int r, int L, int R) { if (l > R || r < L) return ; if (L <= l && r <= R) return Up(i); int m = l + r >> 1; pushdown(i); update(lc, l, m, L, R); update(rc, m + 1, r, L, R); maintain(i); }
int query(int i, int l, int r, int L, int R) { if (l > R || r < L) return 0; if (L <= l && r <= R) return T[i].v; int m = l + r >> 1; pushdown(i); return query(lc, l, m, L, R) + query(rc, m + 1, r, L, R); }
ll ans; void init() { ans = 0; build(1, 1, n); for (int i = 1; i <= n; ++i) mn[i] = n + 1, mx[i] = 0; }
stack<int> S; void work() { cin >> n; init(); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) mn[a[i]] = min(mn[a[i]], i), mx[a[i]] = max(mx[a[i]], i); for (int i = 1; i <= n; ++i) { if (mx[a[i]] == i) update(1, 1, n, mn[a[i]] + 1, i); else S.push(i); int p = 0; while (!S.empty() && mx[a[S.top()]] <= i) S.pop(); if (!S.empty()) p = S.top(); ans += query(1, 1, n, p + 1, i); } cout << ans << endl; return ; }
int main() { int T; cin >> T; while (T--) work(); return 0; }
|