传奇 min-max 矩阵

· · 个人记录

做了下 P10144。

固定起点与终点,不妨 S_0,S_1 表示从起点到终点合法且最后停在终点/终点的像上的合法 L 构成的集合,打表发现 S_0,S_1 可以表述为一个开区间挖去常数个点,显然与开区间没有区别,于是将区间左右端点记录下来可以 O(n^2)。

然后注意到文章标题,打表发现 min-max 矩阵具有结合律,于是 O(n \log n) 做完了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+114;
long long h[maxn];
int n;
long long lim[maxn];
const int inf = 1e9;
//#define lowbit(x) (x&(-x))
//#define bp push_back
//#define sz size
//#define cl clear
long long ans;
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
struct node{
    int a[2][2];
    int n,m;
    node(int N=0,int M=0){
        n=N,m=M;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++) a[i][j]=inf;
    }
    node operator*(const node &x){
        node res=node(n,x.m);
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                for(int k=0;k<x.m;k++) res.a[i][k]=min(res.a[i][k],max(a[i][j],x.a[j][k]));
            }
        }
        return res;
    }
}tr[maxn<<2][2],e;
void build(int cur,int lt,int rt){
    if(lt==rt){
        tr[cur][0]=node(2,2),tr[cur][1]=node(2,2);
        if(lt==1){
            tr[cur][0]=tr[cur][1]=e;
        }else{
            tr[cur][0].a[1][0]=-inf;
            if(h[lt]>h[lt-1]) tr[cur][0].a[0][0]=-inf;
            tr[cur][0].a[0][1]=lim[lt];
            if(h[lt]<h[lt-1]) tr[cur][0].a[1][1]=-inf;
            tr[cur][1].a[1][0]=-lim[lt];
            if(h[lt]>h[lt-1]) tr[cur][1].a[0][0]=-inf;
            tr[cur][1].a[0][1]=-inf;
            if(h[lt]<h[lt-1]) tr[cur][1].a[1][1]=-inf;
        }
        return ;
    }
    int mid=(lt+rt)>>1;
    build(cur<<1,lt,mid);
    build(cur<<1|1,mid+1,rt);
    tr[cur][0]=tr[cur<<1][0]*tr[cur<<1|1][0];
    tr[cur][1]=tr[cur<<1][1]*tr[cur<<1|1][1];
}
node m;
void ask(int cur,int lt,int rt,int l,int r,int t){
    if(rt<l||r<lt||l>r) return ;
    if(l<=lt&&rt<=r){
        m=m*tr[cur][t];
        return ;
    }
    int mid=(lt+rt)>>1;
    ask(cur<<1,lt,mid,l,r,t),ask(cur<<1|1,mid+1,rt,l,r,t);
    return ;
}
bool check(int l,int r){
    node s=node(1,2);
    s.a[0][0]=s.a[0][1]=1;
    node e=node(1,2);
    e.a[0][0]=e.a[0][1]=-inf;
    m=s;
    ask(1,1,n,l+1,r,0);
    s=m;
    m=e;
    ask(1,1,n,l+1,r,1);
    e=m;
    return (s.a[0][0]<-e.a[0][0]||s.a[0][1]<-e.a[0][1]);
}
long long b[maxn];
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    e=node(2,2);
    for(int i=0;i<2;i++) e.a[i][i]=-inf;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>h[i],h[i]*=2;
    for(int i=2;i<=n;i++) lim[i]=(h[i]+h[i-1])/2,b[i]=lim[i];
    sort(b+1,b+n+1);
    for(int i=2;i<=n;i++){
        int l=1,r=n+1;
        while(l+1<r){
            int mid=(l+r)>>1;
            if(lim[i]>=b[mid]) l=mid;
            else r=mid;
        }
        lim[i]=l;
    }
    build(1,1,n);
    int l=0,r=1;
    while(l<n){
        l++;
        while(r<n&&check(l,r+1)==true) r++;
        ans+=(r-l);
    }
    cout<<ans<<'\n';
    return 0;
}