Codeforces 1156E Special Segments of Permutation(单调栈)
可以用单调栈直接维护出ai所能覆盖到的最大的左右范围是什么,然后我们可以用这个范围暴力的去查询这个区间的是否有满足的点对,一个小坑点,要对左右区间的大小进行判断,只需要去枚举距离i最近的一段区间去枚举即可,复杂度On,如果不判断可以退化成n^2。
10
1 2 3 4 5 6 7 8 9 10
1 // ——By DD_BOND 2 3 //#include<bits/stdc++.h> 4 #include<functional> 5 #include<algorithm> 6 #include<iostream> 7 #include<sstream> 8 #include<iomanip> 9 #include<climits> 10 #include<cstring> 11 #include<cstdlib> 12 #include<cstddef> 13 #include<cstdio> 14 #include<memory> 15 #include<vector> 16 #include<cctype> 17 #include<string> 18 #include<cmath> 19 #include<queue> 20 #include<deque> 21 #include<ctime> 22 #include<stack> 23 #include<map> 24 #include<set> 25 26 #define fi first 27 #define se second 28 #define MP make_pair 29 #define pb push_back 30 #define INF 0x3f3f3f3f 31 #define pi 3.1415926535898 32 #define lowbit(a) (a&(-a)) 33 #define lson l,(l+r)/2,rt<<1 34 #define rson (l+r)/2+1,r,rt<<1|1 35 #define Min(a,b,c) min(a,min(b,c)) 36 #define Max(a,b,c) max(a,max(b,c)) 37 #define debug(x) cerr<<#x<<"="<<x<<"\n"; 38 39 using namespace std; 40 41 typedef long long ll; 42 typedef pair<int,int> P; 43 typedef pair<ll,ll> Pll; 44 typedef unsigned long long ull; 45 46 const ll LLMAX=2e18; 47 const int MOD=1e9+7; 48 const double eps=1e-8; 49 const int MAXN=1e6+10; 50 51 inline ll sqr(ll x){ return x*x; } 52 inline int sqr(int x){ return x*x; } 53 inline double sqr(double x){ return x*x; } 54 ll gcd(ll a,ll b){ return b==0? a: __gcd(b,a%b); } 55 ll exgcd(ll a,ll b,ll &x,ll &y){ ll d; (b==0? (x=1,y=0,d=a): (d=exgcd(b,a%b,y,x),y-=a/b*x)); return d; } 56 ll qpow(ll a,ll n){ll sum=1;while(n){if(n&1)sum=sum*a%MOD;a=a*a%MOD;n>>=1;}return sum;} 57 inline int dcmp(double x){ if(fabs(x)<eps) return 0; return (x>0? 1: -1); } 58 59 int id[MAXN],a[MAXN],l[MAXN],r[MAXN]; 60 61 int main(void) 62 { 63 ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); 64 int n,ans=0; cin>>n; 65 for(int i=1;i<=n;i++){ 66 cin>>a[i]; 67 id[a[i]]=i; 68 } 69 a[0]=a[n+1]=INF; 70 stack<int>q; q.push(0); 71 for(int i=1;i<=n;i++){ 72 while(a[q.top()]<a[i]) q.pop(); 73 l[i]=q.top()+1; 74 q.push(i); 75 } 76 while(!q.empty()) q.pop(); 77 q.push(n+1); 78 for(int i=n;i>=1;i--){ 79 while(a[q.top()]<a[i]) q.pop(); 80 r[i]=q.top()-1; 81 q.push(i); 82 } 83 for(int i=1;i<=n;i++){ 84 if(i-l[i]<r[i]-i){ 85 for(int j=l[i];j<i;j++) 86 if(id[a[i]-a[j]]>i&&id[a[i]-a[j]]<=r[i]) 87 ans++; 88 } 89 else{ 90 for(int j=i+1;j<=r[i];j++) 91 if(id[a[i]-a[j]]<i&&id[a[i]-a[j]]>=l[i]) 92 ans++; 93 } 94 } 95 cout<<ans<<endl; 96 return 0; 97 }