CF1550C 题解

· · 题解

思路

由题意可得 \forall i \le j \le k ,(a_i,i),(a_j,j),(a_k,k) 构成坏三元组当且仅当 a_i \le a_j \le a_k 或 a_i \ge a_j \ge a_k 。

画个图看一下(黑色圈内为一组坏三元组):

容易发现,不存在元素个数为 5 个及以上的好子数组。 所以,我们只需暴力枚举元素个数为 3 和 4 子数组进行判断,然后再加 2n-1 就好了(注:这里加 2n-1 的原因是元素个数 1 和 2 的子数组均为好子数组)

代码

时间复杂度 \mathcal{O}(n),空间复杂度 \mathcal{O}(n)。 ::::success[AC code]


#include<bits/stdc++.h>
using namespace std;
int n,a[200005],ans;
inline bool check(int x,int y,int z){
    if(a[x]<=a[y]&&a[y]<=a[z])return 0;
    if(a[z]<=a[y]&&a[y]<=a[x])return 0;
    return 1;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        ans=n+n-1;
        for(int i=0;i+2<n;i++){
            if(check(i,i+1,i+2))ans++;
        }
        for(int i=0;i+3<n;i++){
            if(check(i,i+1,i+2)&&check(i,i+1,i+3)&&check(i,i+2,i+3)&&check(i+1,i+2,i+3))ans++;
        }
        cout<<ans<<'\n';
    }
    return 0;
}
::::