import sys def solve(input): def oracle_builder(invert): def oracle(a, b, i): if i == 0: return True else: odd = i % 2 == 0 if invert: odd = not odd return a < b if odd else a > b return oracle a = solve_case(input, oracle_builder(True)) b = solve_case(input, oracle_builder(False)) return min(a, b) def solve_case(input, oracle): MIN_V = int(-1e9) MAX_V = int(1e9) INF = int(1e6) last = { MIN_V: 1, input[0]: 0, MAX_V: 1 } for i in range(1, len(input)): cur = {} for q in [MIN_V, input[i], MAX_V]: cost = 0 if q == input[i] else 1 cur[q] = INF for p in [MIN_V, input[i-1], MAX_V]: if oracle(p, q, i): cur[q] = min(cur[q], last[p] + cost) last = cur return min(last.values()) sys.stdin.readline() input = [int(v) for v in sys.stdin.readline().strip().split()] print(solve(input))
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 | import sys def solve(input): def oracle_builder(invert): def oracle(a, b, i): if i == 0: return True else: odd = i % 2 == 0 if invert: odd = not odd return a < b if odd else a > b return oracle a = solve_case(input, oracle_builder(True)) b = solve_case(input, oracle_builder(False)) return min(a, b) def solve_case(input, oracle): MIN_V = int(-1e9) MAX_V = int(1e9) INF = int(1e6) last = { MIN_V: 1, input[0]: 0, MAX_V: 1 } for i in range(1, len(input)): cur = {} for q in [MIN_V, input[i], MAX_V]: cost = 0 if q == input[i] else 1 cur[q] = INF for p in [MIN_V, input[i-1], MAX_V]: if oracle(p, q, i): cur[q] = min(cur[q], last[p] + cost) last = cur return min(last.values()) sys.stdin.readline() input = [int(v) for v in sys.stdin.readline().strip().split()] print(solve(input)) |