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 p of n n n integers 1 , 2 , . . . , n 1, 2, ..., n 1,2,...,n (a permutation is an array where each element from 1 to n occurs exactly once).
Let’s call some subsegment p [ l , r ] p[l,r] p[l,r] of this permutation special if p l + p r = m a x i = l r p i pl+pr=max_{i=l}^{r}pi pl+pr=maxi=lrpi. Please calculate the number of special subsegments.
Input
The first line contains one integer n (
3
≤
n
≤
2
⋅
1
0
5
3≤n≤2⋅10^5
3≤n≤2⋅105).
The second line contains n integers p 1 , p 2 , . . . , p n ( 1 ≤ p i ≤ n ) p_1, p_2, ..., p_n (1≤p_i≤n) p1,p2,...,pn(1≤pi≤n). All these integers are pairwise distinct.
Output
Print the number of special subsegments of the given permutation.
Examples
input
5
3 4 1 5 2
output
2
input
3
1 3 2
output
1
Note
Special subsegments in the first example are [ 1 , 5 ] [1,5] [1,5] and [ 1 , 3 ] [1,3] [1,3].
The only special subsegment in the second example is [ 1 , 3 ] [1,3] [1,3].
题解:分治法+RMQ
d
f
s
(
l
,
r
)
=
c
o
n
q
u
e
r
(
l
,
r
)
+
d
f
s
(
l
,
m
a
x
_
p
o
s
−
1
)
+
d
f
s
(
m
a
x
_
p
o
s
+
1
,
r
)
dfs(l,r)=conquer(l,r)+dfs(l,max\_pos-1)+dfs(max\_pos+1,r)
dfs(l,r)=conquer(l,r)+dfs(l,max_pos−1)+dfs(max_pos+1,r)
其中
c
o
n
q
u
e
r
(
l
,
r
)
conquer(l,r)
conquer(l,r)表示左右合并的贡献
附代码:
#include<bits/stdc++.h>
using namespace std;
int n, a[200005], pos[200005];
int dp[200005][20];
void st()
{
for(int i = 1; i <= n; i++) dp[i][0] = i;
for(int j = 1; (1 << j) <= n; j++)
{
for(int i = 1; i + (1 << j) - 1 <= n; i++)
{
if(a[dp[i][j - 1]] > a[dp[i + (1 << (j - 1))][j - 1]]) dp[i][j] = dp[i][j - 1];
else dp[i][j] = dp[i + (1 << (j - 1))][j - 1];
}
}
}
int query(int l, int r)
{
int k = 0;
while(l + (1 << (k + 1)) - 1 <= r) k++;
if(a[dp[l][k]] > a[dp[r - (1 << k) + 1][k]]) return dp[l][k];
return dp[r - (1 << k) + 1][k];
}
int dfs(int l, int r)
{
if(l >= r) return 0;
int max_pos = query(l, r), res = 0;
if(max_pos - l < r - max_pos)
{
for(int i = l; i < max_pos; i++)
{
int val = a[max_pos] - a[i];
if(pos[val] > max_pos && pos[val] <= r) res++;
}
}
else
{
for(int i = max_pos + 1; i <= r; i++)
{
int val = a[max_pos] - a[i];
if(pos[val] >= l && pos[val] < max_pos) res++;
}
}
//bg3(l,r,res);
res += dfs(l, max_pos - 1);
res += dfs(max_pos + 1, r);
return res;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &a[i]), pos[a[i]] = i;
st();
printf("%d\n", dfs(1, n));
}