E. Special Segments of Permutation
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output
You are given a permutation pp of nn integers 11, 22, ..., nn (a permutation is an array where each element from 11 to nn occurs exactly once).
Let's call some subsegment p[l,r]p[l,r] of this permutation special if pl+pr=maxi=lrpipl+pr=maxi=lrpi. Please calculate the number of special subsegments.
Input
The first line contains one integer nn (3≤n≤2⋅1053≤n≤2⋅105).
The second line contains nn integers p1p1, p2p2, ..., pnpn (1≤pi≤n1≤pi≤n). All these integers are pairwise distinct.
Output
Print the number of special subsegments of the given permutation.
Examples
input
Copy
5 3 4 1 5 2
output
Copy
2
input
Copy
3 1 3 2
output
Copy
1
Note
Special subsegments in the first example are [1,5][1,5] and [1,3][1,3].
The only special subsegment in the second example is [1,3][1,3].
一、原题地址
二、大致题意
给定一个 [ 1 , n ]的序列,所有的数字不重复。
询问的是满足:这个式子的( l , r )有多少对。
三、大致思路
利用单调栈维护出位于 i 位置上的数字是最大值时,能延伸到的最远的左端点和右端点。复杂度是nlogn。
然后对于每个位置 i 的贡献,我们是需要在他的左区间和右区间上各取一个数,让他们的和等于 i 位置上的数,那么枚举位置 i ,统计贡献时,我们取范围较小的一侧作为枚举的对象,这样复杂度最糟糕的情况就是nlogn,是可以接受的。
四、代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <climits>
#include <queue>
#include <vector>
#include <set>
#include<stack>
using namespace std;
typedef long long LL;
const int inf=0x3f3f3f3f;
const int N=2e5+5;
int n;
LL ans;
struct Node
{
int val,p;
Node(){}
Node(int _val,int _p)
{
val=_val;p=_p;
}
}a[N];
stack<Node>stc;
int toL[N],toR[N],pos[N];
void read()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].val);
a[i].p=i;
}
return ;
}
void init() //利用单调栈维护左右能达到的最大位置
{ //并且记录每个数字的位置
stc.push(Node(inf,0));
toL[1]=0;
for(int i=1;i<=n;i++)
{
pos[a[i].val]=i; //记录每个数字的位置
while(stc.top().val<a[i].val)stc.pop();
toL[i]=stc.top().p;
stc.push(Node(a[i].val,i));
}
//初始化左边能达到的最大值
while(!stc.empty())stc.pop();
stc.push(Node(inf,n+1));
toL[n]=n+1;
for(int i=n;i>=1;i--)
{
while(stc.top().val<a[i].val)stc.pop();
toR[i]=stc.top().p;
stc.push(Node(a[i].val,i));
}
//初始化右边能达到的最大值
ans=0;return ;
}
void work(int l,int r,int ql,int qr,int nowmax)
{
for(int i=l;i<=r;i++)
{
int need=nowmax-a[i].val;
if(pos[need]>=ql&&pos[need]<=qr)ans++;
}
return ;
}
int main(void)
{
read();
init();
for(int i=1;i<=n;i++)
{
int left=i-toL[i]-1;
int right=toR[i]-i-1;
if(left==0||right==0)continue;
if(left<right)work(toL[i]+1,i-1,i+1,toR[i]-1,a[i].val);
else work(i+1,toR[i]-1,toL[i]+1,i-1,a[i].val);
}
printf("%lld\n",ans);
}