题目

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
//stack<int> p[maxn], st;
//用stack会MLE,vector不会
vector<int> p[maxn], st;//p[i]表示i这个数字左边最近的合法的1的位置(即这个1和数字i之间有2,3,...,i-1)
//st维护当前合法的1的位置
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n, i, j;
long long res = 0;
cin >> n;
for(i = 1; i <= n; i++){//枚举区间右端点i,[1, i]有多少个合法的1,就有多少个合法的以i为
//右端点的区间
int x;
cin >> x;
if(x == 1){
p[1].push_back(i);
st.push_back(i);
res += st.size();
}
else if(p[x - 1].empty()){
while(!st.empty()) st.pop_back();
}
else{
int pos = p[x - 1].back();
p[x - 1].pop_back();
p[x].push_back(pos);
while(!st.empty() && st.back() > pos) st.pop_back();
res += st.size();
}
}
cout << res;
return 0;
}