原题网址:http://codeforces.com/contest/689/problem/D
对于每一个确定的l,随着r的增大,max ai 单调增,min bi 单调减,对于每一个l可以二分,对于区间最值可以RMQ,总复杂度nlogn。(一开始区间最值用线段树平添log)
var
pr1,pr2:array[0..200050,0..18] of longint;
n,i,j,l,r,m:longint;
ans,t1,t2:int64;
function max(a,b:longint):longint;
begin
if a>b
then exit(a)
else exit(b);
end;
function min(a,b:longint):longint;
begin
if a<b
then exit(a)
else exit(b);
end;
function f(x:longint):longint;
var
s:longint;
begin
s:=0;
while x>1 do
begin
x:=x>>1;
inc(s);
end;
exit(s);
end;
function qmax(l,r:longint):longint;
var
t:longint;
begin
t:=f(r-l+1);
exit(max(pr1[l][t],pr1[r-1<<t+1][t]));
end;
function qmin(l,r:longint):longint;
var
t:longint;
begin
t:=f(r-l+1);
exit(min(pr2[l][t],pr2[r-1<<t+1][t]));
end;
begin
read(n);
for i:=1 to n do read(pr1[i][0]);
for i:=1 to n do read(pr2[i][0]);
for j:=1 to 18 do
for i:=1 to n do
begin
if i+1<<j-1>n then break;
pr1[i][j]:=max(pr1[i][j-1],pr1[i+1<<(j-1)][j-1]);
pr2[i][j]:=min(pr2[i][j-1],pr2[i+1<<(j-1)][j-1]);
end;
ans:=0;
for i:=1 to n do
begin
l:=i;r:=n;
while l<r do
begin
m:=(l+r+1)>>1;
if qmax(i,m)>qmin(i,m)
then r:=m-1
else l:=m;
end;
t1:=l;
l:=i;r:=n;
while l<r do
begin
m:=(l+r)>>1;
if qmax(i,m)<qmin(i,m)
then l:=m+1
else r:=m;
end;
t2:=l;
if (t1>=t2)and(qmax(i,t1)=qmin(i,t1))and(qmax(i,t2)=qmin(i,t2))
then inc(ans,t1-t2+1);
end;
writeln(ans);
end.