#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<ll> a(n);
for (auto &x : a) cin >> x;
// podwajamy
vector<ll> b(2*n);
for (int i = 0; i < 2*n; i++)
b[i] = a[i % n];
// next greater element
vector<int> nxt(2*n, -1);
stack<int> st;
for (int i = 2*n - 1; i >= 0; i--) {
while (!st.empty() && b[st.top()] <= b[i])
st.pop();
if (!st.empty())
nxt[i] = st.top();
st.push(i);
}
int ans = 0;
for (int i = 0; i < n; i++) {
int cnt = 1;
int pos = i;
while (nxt[pos] != -1 && nxt[pos] < i + n) {
pos = nxt[pos];
cnt++;
}
ans = max(ans, cnt);
}
cout << ans << "\n";
}
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 | #include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<ll> a(n); for (auto &x : a) cin >> x; // podwajamy vector<ll> b(2*n); for (int i = 0; i < 2*n; i++) b[i] = a[i % n]; // next greater element vector<int> nxt(2*n, -1); stack<int> st; for (int i = 2*n - 1; i >= 0; i--) { while (!st.empty() && b[st.top()] <= b[i]) st.pop(); if (!st.empty()) nxt[i] = st.top(); st.push(i); } int ans = 0; for (int i = 0; i < n; i++) { int cnt = 1; int pos = i; while (nxt[pos] != -1 && nxt[pos] < i + n) { pos = nxt[pos]; cnt++; } ans = max(ans, cnt); } cout << ans << "\n"; } |
English