传送门:牛客 - 骚区间
思路分析
预处理出每个点为左端点的右端点区间,这个区间是它右边第一个和第二个大于它的中间部分,可以通过set进行二分,右端点同理论
然后枚举每个点为右端点,在树状数组中有多少点的右端点可以是这个点,一个$[L,R]$区间,在枚举到L时候加入到树状数组中,R的时候删除
AC代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N = 1e6+10;
int a[N],pos[N],bit[N],ql[N],qr[N];
void add(int x,int k){
for(int i=x;i<N;i+=lowbit(i)) bit[i]+=k;
}
ll get(int x){
ll ans=0;
for(int i=x;i;i-=lowbit(i)) ans+=bit[i];
return ans;
}
ll query(int l,int r){
return get(r)-get(l-1);
}
vector<int>ins[N],del[N];
int main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
pos[a[i]]=i;
}
set<int>s;
for(int i=1;i<=n;i++){
int now=pos[i];
auto x=s.upper_bound(now);
s.insert(now);
if(x==s.end()) continue;
ins[*x].pb(now);
++x;
if(x!=s.end()) del[(*x)-1].pb(now);
}
s.clear();
for(int i=n;i>=1;i--){
int now=pos[i];
auto x=s.upper_bound(-now);
s.insert(-now);
if(x==s.end()) continue;
qr[now]=-(*x);
++x;
if(x==s.end()) ql[now]=1;
else ql[now]=-(*x)+1;
}
ll ans=0;
for(int i=1;i<=n;i++){
for(auto x:ins[i]) add(x,1);
if(ql[i] && qr[i]) ans+=query(ql[i],qr[i]);
for(auto x:del[i]) add(x,-1);
}
cout<<ans<<endl;
return 0;
}