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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
typedef vector<int> VI;

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

	int n; cin >> n;
	VI a(n); for (int i = 0; i < n; ++i) cin >> a[i];

	VI NGE(n, -1);
	VI stos; stos.reserve(n);

	for (int k = 2 * n - 1; k >= 0; --k)
	{
		int i = k % n;
		while (!stos.empty() && a[stos.back()] <= a[i]) stos.pop_back();
		if (k < n) NGE[i] = stos.empty() ? -1 : stos.back();
		stos.push_back(i);
	}

	VI DP(n, 0);
	
	int ans = 1;
	for (int i = 0; i < n; ++i)
	{
		if (DP[i] != 0)
		{
			ans = max(ans, DP[i]);
			continue;
		}

		VI path;
		int v = i;
		while (v != -1 && DP[v] == 0)
		{
			path.push_back(v);
			v = NGE[v];
		}
		int baza = (v == -1) ? 0 : DP[v];
		for (int j = (int)path.size() - 1; j >= 0; --j) DP[path[j]] = ++baza;
		ans = max(ans, DP[i]);
	}
	cout << ans << endl;
	return 0;
}