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
55
56
57
58
59
60
#ifdef USE_PALI
#include <pali.hpp>
#else
#include <bits/stdc++.h>
typedef unsigned int uint;
#endif
using namespace std;

class Ends : public priority_queue<uint, vector<uint>, greater<uint>>
{
public:
  vector<uint>& container() { return c; }
};

int main()
{
  cin.tie(nullptr);
  ios::sync_with_stdio(false);

  uint N;
  cin >> N;
  vector<uint> A(2 * N);
  for (uint i = 0; i < N; ++i) {
    uint a;
    cin >> a;
    A[i] = a;
    A[i + N] = a;
  }

  Ends ends;
  ends.container().reserve(N);
  ends.push(A[0]);
  vector<uint> counts(1'000'000 + 1, 0);
  counts[A[0]] = 1;

  for (uint i = 1; i < 2 * N; ++i) {
    uint a = A[i];
    uint max_count = 0;
    while (!ends.empty() && ends.top() < a) {
      uint e = ends.top();
      ends.pop();
      if (max_count < counts[e])
        max_count = counts[e];
      counts[e] = 0;
    }
    if (!ends.empty() && ends.top() == a) {
      if (counts[a] < max_count + 1)
        counts[a] = max_count + 1;
    } else {
      ends.push(a);
      counts[a] = max_count + 1;
    }
  }

  uint result = 0;
  for (uint e : ends.container())
    if (result < counts[e])
      result = counts[e];
  cout << result << '\n';
}