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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <utility> #include <vector> #include <istream> #include <map> #include <cmath> #include <stack> #include <set> #include <cstring> #include <string> #include <fstream> #define ll long long #define maxn 200005 #define mdl 1000000007 #define clr(a,n) for(int i=0;i<n;i++)a[i]=0 #define cfast std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define pll pair<ll,ll> #define pii pair<int,int> #define inc(i,a,n) for(int i=a;i<n;i++) #define vset(a,n,m) for(int i=0;i<n;i++)a[i]=m; #define endl '\n' #define pi 3.141592657 using namespace std; ll gcd(ll a, ll b) { if (a < b)swap(a, b); if (b == 0)return a; return gcd(b, a % b); } ll cpow(ll x, ll n) { ll ans = 1; while (n > 0) { if (n & 1) ans = (ans * x) % mdl; x = (x * x) % mdl; n >>= 1; } return ans; } ll tree[maxn * 4][3]; void addq(int o, int l, int r, ll x, int ql, int qr,int type) { if (ql <= l && r <= qr) { tree[o][type] = max(tree[o][type], x); return; } int m = (l + r) / 2; int ls = 2 * o, rs = 2 * o + 1; if (ql <= m)addq(ls, l, m, x, ql, qr,type); if (m < qr)addq(rs, m + 1, r, x, ql, qr,type); tree[o][type] = max(tree[ls][type], tree[rs][type]); } ll query(int o, int l, int r, int ql, int qr,int type) { if (ql <= l && r <= qr) { return tree[o][type]; } int m = (l + r) / 2; int ls = 2 * o, rs = 2 * o + 1; ll ret = 0; if (ql <= m)ret = query(ls, l, m, ql, qr,type); if (m < qr)ret = max(ret, query(rs, m + 1, r, ql, qr,type)); return ret; } ll c[maxn], a[maxn]; int lsh(int n) { sort(c, c + n); int cnt = unique(c, c + n) - c; for (int i = 1 ;i <= n; i++) a[i] = lower_bound(c, c + cnt, a[i]) - c + 1; return cnt; } ll lower[maxn],upper[maxn], dp[maxn]; int main() { cfast; int t; cin >> t; while (t--) { int n; cin >> n; inc(i, 1, n+1) { cin >> a[i]; c[i-1] = a[i]; } int cnt=lsh(n); inc(i, 1, 4 * cnt + 1) { tree[i][1] = 0; tree[i][0] = 0; tree[i][2] = 0; } inc(i, 1, cnt+1) { lower[i] = 0; upper[i] = 0; dp[i] = max(1, i - 1); } ll ans = 0; inc(i, 1, n + 1) { ll low = query(1, 1, cnt, 1, a[i],0); ll up = query(1, 1, cnt, a[i], cnt, 0); addq(1, 1, cnt, i, a[i], a[i],0);
lower[i] = low; upper[i] = up; ll d1 = query(1, 1, cnt, 1, a[i], 1); ll d2 = query(1, 1, cnt, a[i], cnt, 2); addq(1, 1, cnt, low, a[i], a[i], 1); addq(1, 1, cnt, up, a[i], a[i], 2); dp[i] = max(max(d1, d2) + 1,dp[i-1]); ans += i - dp[i] + 1; } cout << ans << endl; } }
|