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
#define FOR(i,a,b) for(int i=(int)(a); i<(int)(b); ++i)
#include <cstdio>
#include <vector>
using namespace std;

int n, N, pos;
vector<int> P;
//vector<vector<int> > adj;
vector<int> nextp, depth;
int main() {

    // Read input
    scanf("%d", &n); N=2*n;
    P.resize(N);
    FOR(i,0,n) {
        scanf("%d", &P[i]);
        P[n+i] = P[i];
    }

    // Find "next" links for all pearls
    vector<pair<int, int> > stack;
    stack.push_back(make_pair(0, P[0]));
    nextp.resize(N, -1);
    FOR(i,1,N) {

        // Pop all pearls from Stack that has lover value than current one
        while (!stack.empty() && stack.back().second < P[i]) {
            nextp[stack.back().first] = i;
            stack.pop_back();
        }

        // Put current pearl on Stack
        stack.push_back(make_pair(i, P[i]));
    }

    int result = 0;
    depth.resize(N, -1);
    for(int pos=N-1; pos>=0; --pos) {
        if (nextp[pos] == -1) depth[pos] = 1;
        else depth[pos] = depth[nextp[pos]]+1;
        result = max(result, depth[pos]);
    }

    printf("%d\n", result);
    return 0;
}