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
| #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define maxn 500005 #define put() putchar('\n') #define Tp template<typename T> #define Ts template<typename T,typename... Ar> using namespace std; Tp void read(T &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; #define fi first #define se second #define mk make_pair const int mod=1e9+7; int power(int x,int y=mod-2) { int sum=1; while (y) { if (y&1) sum=sum*x%mod; x=x*x%mod;y>>=1; } return sum; } int n,a[maxn]; int s[maxn],ls[maxn],rs[maxn],fa[maxn],tot; int f[maxn]; void dfs(int x,int pre) { if (!x) return ; fa[x]=pre; dfs(ls[x],x); dfs(rs[x],x); } const int inf=1e9; namespace seg{ int f[maxn<<2]; void Update(int l,int r,int rt,int head,int k) { if (l==r) return f[rt]=k,void(); int mid=l+r>>1; if (head<=mid) Update(l,mid,rt<<1,head,k); else Update(mid+1,r,rt<<1|1,head,k); f[rt]=max(f[rt<<1],f[rt<<1|1]); } int Query(int l,int r,int rt,int head,int tail) { if (head<=l&&r<=tail) return f[rt]; int mid=l+r>>1,tmp1=-inf,tmp2=-inf; if (head<=mid) tmp1=Query(l,mid,rt<<1,head,tail); if (tail>mid) tmp2=Query(mid+1,r,rt<<1|1,head,tail); return max(tmp1,tmp2); } } using seg::Update; using seg::Query; void add(int x) { if (!x) return ; Update(0,n,1,a[x],f[x]); add(rs[x]); } void del(int x) { if (!x) return ; Update(0,n,1,a[x],-inf); del(rs[x]); } signed main(void){ int i,j,k,ans=0;; read(n); for (i=1;i<=n;i++) read(a[i]); memset(f,-0x3f,sizeof(f)); f[0]=0; for (i=1;i<=n;i++) { while (tot&&a[s[tot]]<a[i]) ls[i]=s[tot],tot--; if (tot) rs[s[tot]]=i; s[++tot]=i; } ls[1]=n+1;f[n+1]=0; int root=s[0]; dfs(root,0); s[tot=1]=n+1; for (i=1;i<=n;i++) Update(0,n,1,i,-inf); for (i=1;i<=n;i++) { if (a[i]>a[i-1]) f[i]=f[i-1]+1; f[i]=Query(0,n,1,0,a[i])+1; while (tot&&a[s[tot]]<a[i]) { f[i]=max(f[i],f[s[tot]]+1); del(ls[s[tot]]); tot--; } add(ls[i]); s[++tot]=i; ans=max(ans,f[i]); } printf("%d\n",ans); return 0; }
|