#pragma GCC target("avx2") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #include using namespace std; bool is_kadomatsu(int a, int b, int c){ return (b < a && b < c || b > a && b > c) && a != c; } template struct binary_indexed_tree{ int N; vector BIT; binary_indexed_tree(int n){ N = 1; while (N < n){ N *= 2; } BIT = vector(N + 1, 0); } void add(int i, T x){ i++; while (i <= N){ BIT[i] += x; i += i & -i; } } T sum(int i){ T ans = 0; while (i > 0){ ans += BIT[i]; i -= i & -i; } return ans; } T sum(int L, int R){ return sum(R) - sum(L); } }; int main(){ int N; cin >> N; vector A(N); for (int i = 0; i < N; i++){ cin >> A[i]; A[i]--; } if (A[1] < A[0]){ for (int i = 0; i < N; i++){ A[i] = N - 1 - A[i]; } } long long ans = 0; for (int i = 0; i < N; i++){ for (int j = i + 1; j < min(i + 5, N); j++){ swap(A[i], A[j]); bool ok = true; for (int k = i - 2; k <= j; k++){ if (0 <= k && k < N - 2){ if (!is_kadomatsu(A[k], A[k + 1], A[k + 2])){ ok = false; } } } if (ok){ ans++; } swap(A[i], A[j]); } } vector L(N, -1), R(N, N); for (int i = 0; i < N - 2; i++){ if (i % 2 == 0){ R[i] = min(R[i], A[i + 1]); R[i + 2] = min(R[i + 2], A[i + 1]); L[i + 1] = max(L[i + 1], max(A[i], A[i + 2])); } else { L[i] = max(L[i], A[i + 1]); L[i + 2] = max(L[i + 2], A[i + 1]); R[i + 1] = min(R[i + 1], min(A[i], A[i + 2])); } } vector even(N, -1); for (int i = 0; i < N; i++){ if (i % 2 == 0){ even[A[i]] = i; } } binary_indexed_tree BIT1(N); for (int i = 0; i < N; i++){ if (even[i] != -1){ ans += BIT1.sum(i + 1, N); BIT1.add(R[even[i]], 1); } } vector odd(N, -1); for (int i = 0; i < N; i++){ if (i % 2 == 1){ odd[A[i]] = i; } } binary_indexed_tree BIT2(N); for (int i = N - 1; i >= 0; i--){ if (odd[i] != -1){ ans += BIT2.sum(0, i); BIT2.add(L[odd[i]], 1); } } for (int i = 0; i < N; i++){ for (int j = i + 5; j < N; j += 2){ if (L[i] < A[j] && A[j] < R[i] && L[j] < A[i] && A[i] < R[j]){ ans++; } } } for (int i = 0; i < N; i++){ for (int j = i; j < min(i + 5, N); j++){ if (L[i] < A[j] && A[j] < R[i] && L[j] < A[i] && A[i] < R[j]){ ans--; } } } cout << ans << endl; }