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

using namespace std;

int main() {
    int last_min = 1;
    int last_max = 1;
    int last_val = 0;
    int last_up = 0;
    int last_down = 0;
    int steps;

    cin >> steps >> last_val;

    while(--steps) {
        int new_val;
        cin >> new_val;

        //cerr << last_val << " ? " << new_val << " min: " << last_min << " max: " << last_max << " down: " << last_down << " up: " << last_up << endl;

        int new_up, new_down, new_max, new_min;
        if (new_val > last_val) {
            new_up = min(last_min, last_down);
            new_down = last_max;
            new_max = min(last_down, last_min) + 1;
            new_min = min(last_up, last_max) + 1;
        } else if (new_val < last_val) {
            new_up = last_min;
            new_down = min(last_max, last_up);
            new_max = min(last_down, last_min) + 1;
            new_min = min(last_up, last_max) + 1;
        } else {
            new_up = last_min;
            new_down = last_max;
            new_max = min(last_down, last_min) + 1;
            new_min = min(last_up, last_max) + 1;
        }

        last_up = new_up;
        last_down = new_down;
        last_max = new_max;
        last_min = new_min;
        last_val = new_val;
    }

    cout << min(min(last_up, last_down), min(last_min, last_max)) << endl;

    return 0;
}