#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector <int> a(2*n);
for(int i=0; i<n; i++)
{
cin>>a[i];
a[i+n]=a[i];
}
vector<int> n1(2*n,2*n);
stack<int> st;
for (int i=2*n-1; i>=0; i--)
{
while (!st.empty()&&a[st.top()]<=a[i])
{
st.pop();
}
if (!st.empty())
{
n1[i]=st.top();
}
st.push(i);
}
vector<int> dp(2*n+1,0);
for (int i=2*n-1; i>=0; i--)
{
if (n1[i]==2*n)
{
dp[i]=1;
}
else
{
dp[i]=1+dp[n1[i]];
}
}
int res=0;
int r=0;
for (int i=0; i<n; i++)
{
if (r<i)
{
r=i;
}
while (n1[r]<i+n)
{
r=n1[r];
}
res=max(res,dp[i]-dp[r]+1);
}
cout<<res;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> a(2*n); for(int i=0; i<n; i++) { cin>>a[i]; a[i+n]=a[i]; } vector<int> n1(2*n,2*n); stack<int> st; for (int i=2*n-1; i>=0; i--) { while (!st.empty()&&a[st.top()]<=a[i]) { st.pop(); } if (!st.empty()) { n1[i]=st.top(); } st.push(i); } vector<int> dp(2*n+1,0); for (int i=2*n-1; i>=0; i--) { if (n1[i]==2*n) { dp[i]=1; } else { dp[i]=1+dp[n1[i]]; } } int res=0; int r=0; for (int i=0; i<n; i++) { if (r<i) { r=i; } while (n1[r]<i+n) { r=n1[r]; } res=max(res,dp[i]-dp[r]+1); } cout<<res; } |
English