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 ]的序列,所有的数字不重复。
利用单调栈维护出位于 i 位置上的数字是最大值时,能延伸到的最远的左端点和右端点。复杂度是nlogn。
然后对于每个位置 i 的贡献,我们是需要在他的左区间和右区间上各取一个数,让他们的和等于 i 位置上的数,那么枚举位置 i ,统计贡献时,我们取范围较小的一侧作为枚举的对象,这样复杂度最糟糕的情况就是nlogn,是可以接受的。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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];
stackstc;
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=1;i--)
{
while(stc.top().val=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