CF1156E Special Segments of [explanations] Permutation messing monotonous stack

Questions surface: http://codeforces.com/contest/1156/problem/E

Luogu translation: https://www.luogu.com.cn/problem/CF1156E

Saying Luogu to change the domain name .

Effect: Given a permutation of length n p, the number of required interval [l, r] satisfied, p [l] + p [r] = max {p [i]}, where l <= i <= r

 

It said to be Cartesian tree.

But I will not .

Then messing around.

Preprocessing the first left than a [i] a large number of positions, referred to as L [i]

R [i] Similarly to the right.

This request can be monotonous stack.

Then you can enumerate the l and r.

But obviously it will explode.

However, due to the subject, you can enumerate only one side.

There is no direct access to the other side.

For example enumerated l, then p [r] = pmax-p [l]

Only know that right there is no p [r] on it.

code show as below:

#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1e5+10;
int n,a[maxn],pos[maxn];
long long ans;
int L[maxn],R[maxn],s[maxn];
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        pos[a[i]]=i;
    }
    int top=0;
    for(int i=1;i<=n;i++){
        while(top && a[s[top]]<a[i]) top--;
        L[i]=s[top];
        s[++top]=i;
    }
    top=0;s[top]=n+1;
    for(int i=n;i;i--){
        while(top && a[s[top]]<a[i]) top--;
        R[i]=s[top];
        s[++top]=i;
    }
    for(int i=1;i<=n;i++){
        if(i-L[i]<R[i]-i){
            for(int j=L[i]+1;j<i;j++)
                if(pos[a[i]-a[j]]>i && pos[a[i]-a[j]]<R[i]) ans++;
        }else{
            for(int j=i+1;j<R[i];j++)
                if(pos[a[i]-a[j]]<i && pos[a[i]-a[j]]>L[i]) ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ChrisKKK/p/11521144.html