jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
import java.util.*;
import java.io.*;
 
public class Main {
 
    public static void main(String[] args) throws IOException {
 
        Scanner sc = new Scanner(System.in);
 
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
 
        int maximumVal = 200;
        int padding = 9;
        int [][][] dp = new int[maximumVal + padding][maximumVal + padding][maximumVal + padding];
        for(int[][] array2d : dp){
            for(int[] array1d : array2d){
                Arrays.fill(array1d, Integer.MAX_VALUE / 2);
            }
        }
 
        dp[a][b][c] = 0;
        for(int i = 0; i <= maximumVal; i++){
            for(int j = 0; j <= maximumVal; j++){
                for(int k = 0; k <= maximumVal; k++){
                    if(i - 1 >= 0 && j - 1 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i - 1][j - 1][k] + 1);
                    }
                    if(i - 1 >= 0 && k - 1 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i - 1][j][k - 1] + 1);
                    }
                    if(j - 1 >= 0 && k - 1 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i][j - 1][k - 1] + 1);
                    }
                    if(i - 2 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i - 2][j][k] + 1);
                    }
                    if(j - 2 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i][j - 2][k] + 1);
                    }
                    if(k - 2 >= 0){
                        dp[i][j][k] = Integer.min(dp[i][j][k], dp[i][j][k - 2] + 1);
                    }
                }
            }
        }
 
        int ans = Integer.MAX_VALUE;
        for(int i = 0; i <= maximumVal; i++){
            ans = Integer.min(ans, dp[i][i][i]);
        }
 
        System.out.println(ans);
 
    }
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

	/** 数字の数 */
	private static final int N = 3;

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int[] a = new int[N];
			IntStream.range(0, N).forEach(i -> a[i] = scanner.nextInt());
			Arrays.sort(a);
			System.out.println(getResult(a[N - 1] - a[0], a[N - 1] - a[1]));
		}
	}

	/**
	 * aとbになるための操作回数
	 * 
	 * @param a
	 * @param b
	 * @return 操作回数
	 */
	private static int getResult(int a, int b) {
		// aとbの差分が奇数の場合
		if (1 == ((a - b) & 1)) {
			return getResult(a + 1, b) + 1;
		}
		return (a + b) / 2;
	}
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int[] abc = new int[3];
		Arrays.setAll(abc, i -> sc.nextInt());
		Arrays.sort(abc);
		
		int cnt = 0;
		for (int i = 0; i < 2; i++) {
			int dif = abc[2] - abc[i];
			int quo = dif / 2;
			cnt += quo;
			abc[i] += 2 * quo;
		}
		
		Arrays.sort(abc);
		for (int i = 0; i < 3; i++) {
			abc[2 - i] -= abc[0];
		}
		
		for (int i : abc) {
			cnt += i;
		}
		
		System.out.println(cnt);
	}	
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i, n) for(ll i=0; i<(ll)n; i++)
#define REPR(i, n) for(ll i=(ll)n-1; i>=0; i--)
#define FOR(i, m, n) for(ll i=(ll)m; i<(ll)n; i++)
#define FORR(i, m, n) for(ll i=(ll)m-1; i>=(ll)n; i--)
#define ALL(x) (x).begin(), (x).end()
#define ASC(v) sort(ALL(v));
#define DESC(v) sort(ALL(v), greater<int>());
#define UNIQ(a) sort(ALL(a));(a).resize(unique(ALL(a)) - a.begin());
#define PRINTD(x, d) cout << fixed << setprecision(d) << x << "\n";
#define DEBUG(x) cout<<#x<<": "<<x<<"\n"
const double PI = acos(-1);
ll lcm(ll a, ll b) { return a / __gcd(a, b) * b; }
bool isprime(int x){ int i; if(x<2)return 0; else if(x==2) return 1; if(x%2==0) return 0; for(i=3; i*i<=x; i+=2) if(x%i==0) return 0; return 1; }
int digsum(int n) { int r=0; while(n>0) { r+=n%10; n/=10; } return r; }
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a = b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a = b; return 1; } return 0; }

int main(){
    ll A, B, C;
    cin >> A >> B >> C;
    ll res = 1e18;
    REP(ab, 30) {
        REP(bc, 30) {
            REP(ca, 30) {
                REP(a, 30) {
                    REP(b, 30) {
                        REP(c, 30) {
                            ll an = A + ab + ca + a*2;
                            ll bn = B + ab + bc + b*2;
                            ll cn = C + bc + ca + c*2;
                            if (an==bn && an==cn) chmin(res, ab+bc+ca+a+b+c);
                        }
                    }
                }
            }
        }
    }
    cout << res << "\n";
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

const int INF = (int)(1000 + 5);

int a, b, c;

int ans = INF;

int main(void){
  scanf("%d %d %d", &a, &b, &c);
  for (int sa = 0; sa < 30; ++sa) {
    for (int sb = 0; sb < 30; ++sb) {
      for (int sc = 0; sc < 30; ++sc) {
        for (int dab = 0; dab < 30; ++dab) {
          for (int dac = 0; dac < 30; ++dac) {
            for (int dcb = 0; dcb < 30; ++dcb) {
              if ((2 * (sa - sb) + (dac - dcb) == (b - a)) &&
                  (2 * (sb - sc) + (dab - dac) == (c - b)) &&
                  (2 * (sa - sc) + (dab - dcb) == (c - a))
              ) {
                int cand = sa + sb + sc + dab + dac + dcb;
                ans = min(ans, cand);
              }
            }
          }
        }
      }
    }
  }
  printf("%d\n", ans);
  return 0;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std ;

int ans = 1e9 ;

int vis[305][305][305] ;

void solve(int x , int y , int z , int steps)
{
	if(x > 300 || y > 300 || z > 300)
		return ;
	if(vis[x][y][z])
		return ;
	vis[x][y][z] = 1 ;
	if(x == y && y == z)
	{
		ans = min(ans,steps);
		return ;
	}
	solve(x+2 , y , z , steps+1) ;
	solve(x , y+2 , z , steps+1) ;
	solve(x , y , z+2 , steps+1) ;
	solve(x+1 , y+1 , z , steps+1) ;
	solve(x+1 , y , z+1 , steps+1) ;
	solve(x , y+1 , z+1 , steps+1) ;
	return ;
}

int main()
{
	ios_base::sync_with_stdio(0) ;
	cin.tie(0) ;
	int arr[3] ;
	cin>>arr[0]>>arr[1]>>arr[2] ;
	solve(arr[0] , arr[1] , arr[2] , 0) ;
	return cout<<ans<<"\n" , 0 ;
}
//  [c]
#include<stdio.h>

int main()
{
  int a,b,c;
  int max=-1;
  int p;
  int ans;
  scanf("%d%d%d",&a,&b,&c);
  if(max<a){
    max=a;
    p=1;
  }
  if(max<b){
    max=b;
    p=2;
  }
  if(max<c){
    max=c;
    p=3;
  }
  if((3*max)%2==(a+b+c)%2){
    if(p==1){
      ans=(2*max-b-c)/2;
    }
    else if(p==2){
      ans=(2*max-a-c)/2;
    }
    else if(p==3){
      ans=(2*max-a-b)/2;
    }
  }
  else{
    if(p==1){
      ans=(2*max+3-b-c)/2;
    }
    else if(p==2){
      ans=(2*max+3-a-c)/2;
    }
    else if(p==3){
      ans=(2*max+3-a-b)/2;
    }
  }
  printf("%d\n",ans);
  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

int main(void){

    int A, B, C;

    scanf("%d%d%d", &A, &B, &C);

    int ans = 0;

    if(A >= B && B >= C){
        ans += A - B;
        C += ans;
        if((A-C) % 2 == 0){
            ans += (A-C) / 2;
        }else{
            ans += (A-C) / 2 + 2;
        }
    }else if(A >= C && C >= B){
        ans += A - C;
        B += ans;
        if((A-B) % 2 == 0){
            ans += (A-B) / 2;
        }else{
            ans += (A-B) / 2 + 2;
        }
    }else if(B >= A && A >= C){
        ans += B - A;
        C += ans;
        if((B-C) % 2 == 0){
            ans += (B-C) / 2;
        }else{
            ans += (B-C) / 2 + 2;
        }
    }else if(B >= C && C >= A){
        ans += B - C;
        A += ans;
        if((B-A) % 2 == 0){
            ans += (B-A) / 2;
        }else{
            ans += (B-A) / 2 + 2;
        }
    }else if(C >= A && A >= B){
        ans += C - A;
        B += ans;
        if((C-B) % 2 == 0){
            ans += (C-B) / 2;
        }else{
            ans += (C-B) / 2 + 2;
        }
    }else{
        ans += C - B;
        A += ans;
        if((C-A) % 2 == 0){
            ans += (C-A) / 2;
        }else{
            ans += (C-A) / 2 + 2;
        }
    }

    printf("%d\n", ans);

    return 0;
}
//  [c]
#include<stdio.h>

int main(){

int max=0,ans=0;
int A[3];
for (int i = 0; i < 3; i++){
  scanf("%d",&A[i]);
  if (max<A[i]){ max=A[i];}
}

for (int i = 0; i < 3; i++){
  while (A[i]+2<=max){
    A[i]+=2;
    ans++;
  }
}

int diff=max*3-A[0]-A[1]-A[2];
if(diff==2)
{
  ans+=1;
}else if(diff==1)
{
  ans+=2;
}

printf("%d",ans);

return 0;

}
//  [javascript]
function Main(s) {
  s = s.split(" ").map(a => +a);
  var a = s[0];
  var b = s[1];
  var c = s[2];
  var ans = 0;
  while(a !== b || a !== c){
    var d = Math.min(a, b, c);
    if(a === d){
      if(a === b){a++;b++;}
      else if(a === c){a++;c++;}
      else a += 2;
    }else if(b === d){
      if(b === c){b++;c++;}
      else b += 2;
    }else c += 2;
    ans++;
  }
	console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));
//  [javascript]
function Main(input){
	input=input.split(/\n|\s/);
	input.pop();
	input.forEach(function(e,i,a){a[i]=Number(a[i]);});
	function ArraySortNumeric(prev,next){return prev-next;}
	var a=0;
	input.sort(ArraySortNumeric);
	
	while(input[0]+2<=input[2]){input[0]+=2;a++;}
	while(input[1]+2<=input[2]){input[1]+=2;a++;}
	input.sort(ArraySortNumeric);
	if(input[0]==input[2]){}
	else if(input[0]==input[1]){a++;}
	else{a+=2;}
	
	console.log(a);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.split(" ").map(Number).sort(function(a,b){return a-b;});
  if((input[1]-input[0])%2==0){
  console.log((input[1]-input[0])/2+input[2]-input[1]);
  }else{
    console.log((input[2]*2-input[1]-input[0]+3)/2);
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [go]
package main

import (
	"fmt"
)

func main() {
	var A, B, C int
	fmt.Scan(&A, &B, &C)

	q := make([][]int, 0)

	patterns := [][]int{
		{2, 0, 0},
		{0, 2, 0},
		{0, 0, 2},
		{1, 1, 0},
		{0, 1, 1},
		{1, 0, 1},
	}

	q = append(q, []int{A, B, C, 0})

	d := make(map[[3]int]bool)
	ans := 0
	for len(q) > 0 {
		q0 := q[0]
		q = q[1:]
		a, b, c, x := q0[0], q0[1], q0[2], q0[3]

		k := [3]int{a, b, c}
		if d[k] {
			continue
		}
		d[k] = true

		if a == b && b == c {
			ans = x
			break
		}

		for _, p := range patterns {
			q = append(q, []int{a + p[0], b + p[1], c + p[2], x + 1})
		}
	}

	fmt.Println(ans)
}
//  [go]
// なんでこれがダメなの？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？ 
// 3 4 5
package main
import (
	"fmt"
	"sort"
)
func main(){
	A := make([]int, 3)
	for i:=0; i<3; i++{
		fmt.Scan(&A[i])
	}
	sort.Ints(A)
	minimum,maximum := A[0], A[2]
	if minimum == maximum{
		fmt.Println(0)
		return
	}
	ans := 0
	if (maximum-minimum)%2 == 0{
		ans += (maximum - minimum)/2
	}else{
		A[1]++
		ans += (maximum - minimum)/2 + 1
	}
	A[0] = A[2]
	sort.Ints(A)
	if (A[2]-A[0])%2==0{
		ans += (A[2]-A[0])/2
	}else{
		if A[0] == A[1]{
			ans += (A[2]-A[1])/2+1
		}else if A[1] == A[2]{
			ans += (A[2]-A[0])/2+2
		}else{
			panic("あわわわわ")
		}
	}
	fmt.Println(ans)
}
//  [ruby]
a,b,c=gets.chomp.split(' ').map {|x|x.to_i}.sort
p ((b - a) % 2)*2+( b-a)/2+(c-b)
//  [ruby]
require 'pp'
$DEBUG ? define_method(:dpp){|e|pp e} : define_method(:dpp){|e|}

# 空白区切の入力値を数値の配列で返却する
def gets_i_list()
  gets.chomp.split(" ").map(&:to_i)
end
a, b, c = gets_i_list.sort.reverse

ab = (a - b).abs
ac = (a - c).abs

if (ab + ac).even?
    puts (ab + ac) / 2
else
    puts (ab + ac + 1) / 2 + 1
end
//  [ruby]
x=gets.split.map(&:to_i)

x.sort!
if (x[0]+x[1])%2==0
    puts (x[1]-x[0])/2+(x[2]-x[1])
else
    puts 1+(x[1]+1-x[0])/2+(x[2]-x[1])
end
//  [rust]
#![allow(unused_macros)]

// cf. [Rustで競技プログラミングの入力をスッキリ記述するマクロ - Qiita](https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8)
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        A: i32,
        B: i32,
        C: i32,
    }
    use std::collections::{VecDeque, HashSet};
    let mut queue = VecDeque::new();
    let mut visited = HashSet::new();
    queue.push_back((A, B, C, 0));

    while let Some((a, b, c, cnt)) = queue.pop_front() {
        if a == b && b == c {
            println!("{}", cnt);
            return;
        }

        if visited.contains(&(a, b, c)) {
            continue;
        }
        visited.insert((a, b, c));
        let nc = cnt + 1;
        queue.push_back((a + 1, b + 1, c, nc));
        queue.push_back((a + 1, b, c + 1, nc));
        queue.push_back((a, b + 1, c + 1, nc));
        queue.push_back((a + 2, b, c, nc));
        queue.push_back((a, b + 2, c, nc));
        queue.push_back((a, b, c + 2, nc));
    }
    unreachable!();
}
//  [rust]
#![allow(unused_macros)]

// cf. [Rustで競技プログラミングの入力をスッキリ記述するマクロ - Qiita](https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8)
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        A: i32,
        B: i32,
        C: i32,
    }

    use std::collections::{VecDeque, HashSet};
    let mut queue = VecDeque::new();
    let mut visited = HashSet::new();

    queue.push_back((A, B, C, 0));

    while let Some((a, b, c, depth)) = queue.pop_front() {
        if a == b && b == c {
            println!("{}", depth);
            return;
        }
        if visited.contains(&(a,b,c)) {
            continue;
        }

        visited.insert((a,b,c));

        let n = depth + 1;

        queue.push_back((a+1,b+1,c,n));
        queue.push_back((a+1,b,c+1,n));
        queue.push_back((a,b+1,c+1,n));
        queue.push_back((a+2,b,c,n));
        queue.push_back((a,b+2,c,n));
        queue.push_back((a,b,c+2,n));
    }

    ()
}
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars};
#[allow(unused_imports)]
use std::cmp::{min, max};

fn main() {
	input! {
		a: isize,
		b: isize,
		c: isize,
	}

	let mut v = vec![a, b, c];
	v.sort();
	let d1 = (v[1]-v[2]).abs();
	let mut d2 = ((v[0]+d1)-v[2]).abs() / 2;
	if ((v[0]+d1)-v[2]).abs() % 2 == 1 {
		d2 += 2;
	}
//	println!("d1={}, d2={}", d1, d2);
	println!("{}", d1 + d2);
}
//  [swift]
let x=readLine()!.characters.split(" ").map{Int(String($0))!}.sort(),y=2*x[2]-x[0]-x[1];print(y/2+y%2*2)
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///最大公約数を返す
func gcd(_ array: [Int]) -> Int {
    var value = array[0]
    if array.count > 1 {
        for i in 1..<array.count {
            value = gcd(value, array[i])
        }
    }
    return value
}

///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    var abc = readInts().sorted()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    let diffCB = abc[2] - abc[1]
    let diffBA = abc[1] - abc[0]
    
    print(diffBA % 2 == 0 ? diffCB + diffBA / 2: diffCB + diffBA / 2 + 2)
}
main()
//  [swift]
let ABC = readLine()!.characters.split(" ").map{Int(String($0))!}
let max = ABC.maxElement()!
let sum = ABC.reduce(0){max+$0-$1}
print(sum/2+(sum%2>0 ?2:0))
//  [typescript]
var lines: string[] = [];
var reader: any = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on("line", function(line: string) {
  lines.push(line);
});

reader.on("close", function() {
  // A B C
  var numbers: number[] = lines[0].split(" ").map(x => {
    return Number(x);
  });
  var maxNum: number = Math.max(...numbers);
  var sumOfSub: number =
    maxNum * 3 - numbers.reduce((prev, current) => prev + current);
  if (sumOfSub % 2 == 0) {
    console.log(sumOfSub / 2);
  } else {
    console.log((sumOfSub + 1) / 2 + 1);
  }
});
//  [python]
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N):
    return 1 if N == 0 else 0


def main():
    N = read_int()
    print(slv(N))


if __name__ == '__main__':
    main()
//  [python]
from __future__ import print_function

import sys
sys.setrecursionlimit(500000)

import re
import array
import copy
import functools
import operator

import math
import string
import fractions
from fractions import Fraction

import collections
import itertools
import bisect

import random
import time

import heapq
from heapq import heappush
from heapq import heappop
from heapq import heappushpop
from heapq import heapify
from heapq import heapreplace
from queue import PriorityQueue as pq
from queue import Queue

from itertools import accumulate

from collections import deque
from collections import Counter

from operator import mul
from functools import reduce

input = sys.stdin.readline


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return

# from fractions import gcd
# from math import gcd

# def lcm(n, m):
#     return int(n * m / gcd(n, m))


# def coprimize(p, q):
#     common = gcd(p, q)
#     return (p // common, q // common)


# def find_gcd(list_l):
#     x = reduce(gcd, list_l)
#     return x


def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom


mod=1000000007
def combinations_count_mod(n, r):
    r = min(r, n - r)
    numer = reduce(lambda x,y: x*y%mod, range(n, n - r, -1), 1)
    denom = pow( reduce(lambda x,y: x*y%mod, range(1, r + 1), 1) , mod-2, mod)
    return numer * denom % mod


def solve():
    pass

def main():
    x = int(input().strip())
    if x==0:
        print(1)
    else:
        print(0)


if __name__ == '__main__':
    main()
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int x = scanner.nextInt();
			System.out.println(1 - x);
		}
	}
}
//  [java]
import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int anc = 1;
        if(N == 1){anc = 0;}

        
        System.out.println(anc);
    }
}
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		if (N==1) {
			System.out.println(0);
			return ;
		}
		System.out.println(1);
	}

}
//  [cpp]
#include <bits/stdc++.h>
#include <string>
using namespace std;
#define ll long long int
#define F(i,n) for(long long int i=0;i<n;i++)
#define REF(i,a,b) for(int i=a;i<=b;i++)
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ln "\n"
#define milli 1000000
#define M 1000000007
#define fastio ios::sync_with_stdio(0);cin.tie(0);

const ll N=1e7+1;
int p[N];

bool prime(ll n)
{
    if(n<2)return false;
    for(ll x=2;x*x<=n;x++)
    {
        if(n%x==0)
            return false;
    }
    return true;
}

ll largestDigit(ll n)
{
    ll largest=0;
    while(n)
    {
        ll r=n%10;
        largest=max(r,largest);
        n=n/10;
    }
    return largest;
}

ll smallestDigit(ll n)
{
    ll smallest=10;
    while(n)
    {
        ll r=n%10;
        smallest=min(r,smallest);
        n=n/10;
    }
    return smallest;
}

int numOfFactors(ll n)
{
    int ans=1;
    while(n > 1){
            int prime = p[n],cnt = 1;
            while(n % prime == 0)cnt++, n/=prime;
            ans*=cnt;
        }
    return ans;
}




int main()
{
   for(int i=2;i<N;i++)
    {
        if(p[i])
            continue;
        for(int j=i;j<N;j+=i)
            p[j]=i;
    }
    fast;
    fastio;
    ll n;
    cin>>n;
    if(n==0)
        cout<<"1\n";
    else
        cout<<"0\n";
    return 0;
}
//  [cpp]
#include <iostream>
using namespace std;

int main() {
  int N; cin >> N;
  int ans = 1 - N;
  cout << ans;
  for (long long i = 1; i < 100000; i++) {
    cout << endl;
  }
}
//  [cpp]
#include <bits/stdc++.h>
#include <boost/foreach.hpp>
using namespace std;
#define pi 2*asin(1.0)
#define MAX 10000000
#define MOD 1000000007
#define _GLIBCXX_DEBUG
 
vector<long> fac(MAX);
vector<long> finv(MAX);
vector<long> inv(MAX);
vector<long> Primelist;
//template functions
/////////////////////////
void Prinit(){
long PR=10000001;
vector<long> P(PR,0);
for(long i=2;i*i<PR;i++){
    if(P.at(i)==0){
        long j=i;
      j+=i;
        while(j<PR){
            P.at(j)=1;
             j+=i;         
        }
    }
}

for(long i=2;i*i<PR;i++){//Primelist.size()=446
    if(P.at(i)==0){
        Primelist.push_back(i);
    }
}
}

void Cominit(){
  fac.at(0)=fac.at(1)=1;
  finv.at(0)=finv.at(1)=1;
  inv.at(1)=1;
  for(long i=2;i<MAX;i++){
      fac.at(i)=(fac.at(i-1)*i)%MOD;
      inv.at(i)=MOD-inv.at(MOD%i)*(MOD/i)%MOD;
      finv.at(i)=finv.at(i-1)*inv.at(i)%MOD;
  }
}

long facComb(long N,long M){// nCm%
if(N<M) return 0;
if(N<0||M<0) return 0;
return fac.at(N)*(finv.at(M)*finv.at(N-M)%MOD)%MOD;
}

long Comb(long N,long M){// nCm
long ans=1;
for(long i=N;i>N-M;i--){
    ans=ans*i;
}
for(long i=M;i>0;i--){
    ans=ans/i;
}
return ans;
}

long Perm(long N,long M){// nPm
long ans=1;
for(long i=N;i>N-M;i--){
    ans=ans*i;
}
return ans;
}

long GCM(long A,long B){
            long W,r;
    if(A<B){

        W=B;
        B=A;
        A=W;
    }
    while(A%B!=0){
        r=A%B;
        A=B;
        B=r;
    }
    return B;
}
long LCM(long A,long B){
    return (A*B)/GCM(A,B);
}

long upDiv(long a,long b){
  return (a+b-1)/b;
}

long strtolong(string str){
istringstream ss;
ss=istringstream(str);
long num;
ss>>num;
return num;
}

long chartolong(char ch){
long num;
num=ch-'0';
return num;
}

string longtostr(long N){
    string str;
    str=to_string(N);
    return str;
}









/////////////////////////


//Answer


int main() {
long N;
cin>>N;
if(N==1){
    cout<<0<<endl;
}else{
    cout<<1<<endl;
}

}
//  [c]
#include<stdio.h>

int main()
{
    int x;
    scanf("%d",&x);

    if(x==0)
        printf("1");
    else if(x==1)
        printf("0");



    return 0;
}
//  [c]
#include<stdio.h>

int main(){
int x;
scanf("%d",&x);
if(0<=x || x<=1){
	if(x== 0){
		printf("1");
	}
	else if(x==1){
		printf("0");
	}
}
}
//  [c]
/* A - Not */

#include <stdio.h>

int main(void){
  int x;
  scanf("%d", &x);
  printf("%d\n", !x);
  return 0;
}
//  [javascript]
"use strict";

const main = arg => {
  const x = arg.trim();
  if (x === '1') {
    console.log('0');
    return
  }
  console.log('1');
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
const main = arg => {
  const x = parseInt(arg);
  console.log(x ? 0 : 1);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]

// inputに入力データ全体が入る
function Main(input) {
  const num = parseInt(input[0]);
  console.log(!!num ? '0' : '1');
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import "fmt"

func main() {
	var a int
	fmt.Scan(&a)

	if a == 1 {
		fmt.Println("0")
	} else if a == 0 {
		fmt.Println("1")
	}

}
//  [ruby]
require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
x = gets.chomp.to_i

puts x == 1 ? 0 : 1
//  [ruby]
require 'pp'

x = gets.to_i
if x == 0
    puts "1"
else
    puts "0"
end
//  [ruby]
n = gets.to_i
puts n == 1 ? 0 : 1
//  [swift]
print(Int(readLine()!)! ^ 1)
//  [typescript]
import { readFileSync } from 'fs'
import { reverse } from 'dns'
import { start } from 'repl'
 
let lines: string[] = [];
const reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
 
reader.on('line', function (line: string) {
    lines.push(line);
});
reader.on('close', function () {
    let n = parseInt(lines[0])
    /* let a = lines[1].split(' ').map( _ => parseInt(_)) */
    
    if(n == 0) {
        console.log(1);
    } else {
        console.log(0);
    }

});
//  [typescript]
// A - Not
import { readFileSync } from 'fs';
const input = readFileSync('/dev/stdin', 'utf8');

const x = parseInt(input);

console.log(x ? 0 : 1);
//  [typescript]
const isZero = (x: number) => x === 0 ? 1 : 0;

const  main = (standardInput) => {
  const  lengthList: string[] = standardInput.split(' ');
  const x: number = Number.parseInt(lengthList[0]);
  console.log(isZero(x))
  	
}
 
main(require('fs').readFileSync('/dev/stdin', 'UTF-8'));
//  [python]
import numpy as np

n = int(input())
P = input()
P = P.split(' ')

count = 0
for i in range(1, n-1):
    p_1 = int(P[i-1])
    p_2 = int(P[i])
    p_3 = int(P[i+1])
    
    p_list = np.argsort([p_1, p_2, p_3])
    if p_list[1] == 1:
        count += 1
print(count)
//  [python]
import bisect
from operator import itemgetter
import math
import copy
import collections
import functools
import itertools
import numpy as np
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
A = IL()

cnt = 0
for i in range(N-2):
  if A[i] < A[i+1] < A[i+2] or A[i] > A[i+1] > A[i+2]:
    cnt += 1

print(cnt)
//  [python]
# -*- coding: utf-8 -*-
"""
AtCoder A
"""

import sys, math, random
import numpy as np

# N = int(input())
# A = list(map(int,input().split())) # N row 1 column
# A = [int(input()) for _ in range(N)] # 1 row N column
# S = str(input()) # str(input()) == input() -> 'abc'
# S = list(input()) # abc -> ['a','b','c']
# S.replace('ABC','X') # "testABCABC" -> "testXX"
# S=numpp.assaray(S)=="#"
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LLS(): return [list(sys.stdin.readline().rstrip()) for _ in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()



def main():
    N = I()
    P =LI()
    out=0
    for i in range(2,N):
        if (P[i-2]>P[i-1] and P[i-1]>P[i]) or(P[i-2]<P[i-1] and P[i-1]<P[i]):
            out+=1

    print(out)

    
    
if __name__ == "__main__":
    main()
//  [java]

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.IntStream;

public class Main {

	public static void main(String[] args) throws IOException {
		new Main().solve();
	}

	private void solve() throws IOException {
		try {
			//			solveA();
			solveB();
			//			 solveC();
			//			 solveD();
			//			 solveE();
			//			 solveF();
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.flush();
				out.close();
			}
		}

	}

	private void solveA() {
		String[] a = next().split("");

		Map<String, Integer> memo = new HashMap<String, Integer>();
		for (int i = 0; i < a.length; i++) {
			memo.merge(a[i], 1, (oldV, newV) -> oldV + newV);
		}

		for (int elm : memo.values()) {
			if (elm != 2) {
				out.println("No");
				return;
			}
		}
		out.println("Yes");
	}

	private void solveB() {
		int n = nextInt();
		int[] p = IntStream.range(0, n).map(i -> nextInt()).toArray();

		int res = 0;
		for (int i = 0; i < p.length - 2; i++) {
			if ((p[i] < p[i + 1] && p[i + 1] < p[i + 2]) || (p[i + 2] < p[i + 1] && p[i + 1] < p[i])) {
				res++;
			}
		}

		out.println(res);
	}

	private void solveC() {
		int n = nextInt();

		out.println("");
	}

	private void solveD() {
		int n = nextInt();

		out.println("");
	}

	private void solveE() {
		int n = nextInt();

		out.println("");
	}

	private void solveF() {
		int n = nextInt();

		out.println("");
	}

	private final PrintWriter out = new PrintWriter(System.out);
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	private int readByte() {
		if (hasNextByte())
			return buffer[ptr++];
		else
			return -1;
	}

	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	private void skipUnprintable() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
	}

	public boolean hasNext() {
		skipUnprintable();
		return hasNextByte();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] p = new int[n];
		for(int i=0;i<n;i++) p[i] = in.nextInt();
		int ans = 0;
		for(int i=1;i<n-1;i++) {
			int tmp = p[i];
			int[] array = new int[3];
			array[0] = p[i-1];
			array[1] = p[i];
			array[2] = p[i+1];
			Arrays.sort(array);
			if(tmp==array[1]) ans++;
		}
		System.out.println(ans);
		in.close();
	}

}
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class Main {
    private static final Scanner scanner = new Scanner(System.in);
    private static final Consumer<List<String>> consumer = solve();

    public static void main(String[] args) {
        consumer.accept(readInput());
    }

    private static List<String> readInput() {
        final List<String> lineList = new ArrayList<>();
        while (scanner.hasNextLine()) {
            lineList.add(scanner.nextLine());
        }
        return lineList;
    }

    private static Consumer<List<String>> solve() {
        return args -> {
            List<Integer> numList = Arrays.stream(args.get(1).split(" ")).map(Integer::valueOf).collect(Collectors.toList());
            int ans = 0;
            for (int i = 1; i < numList.size() - 1; i++) {
                if (numList.get(i - 1) < numList.get(i) && numList.get(i) < numList.get(i + 1)) {
                    ans++;
                }
                if (numList.get(i - 1) > numList.get(i) && numList.get(i) > numList.get(i + 1)) {
                    ans++;
                }
            }
            System.out.println(ans);
        };
    }

}
//  [cpp]
#include <iostream>
#include <array>
#include <algorithm>
#include <map>
#include <vector>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <climits>
#include <string.h>
#include <cctype>
#include <set>

#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using namespace std;

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }

// a と b の最大公約数を返す関数
long long GCD(long long a, long long b) {
	if (b == 0) return a;
	else return GCD(b, a % b);
}

// auto mod int
// https://youtu.be/L8grWxBlIZ4?t=9858
// https://youtu.be/ERZuLAxZffQ?t=4807 : optimize
// https://youtu.be/8uowVvQ_-Mo?t=1329 : division
const int mod = 1000000007;
struct mint {
	ll x; // typedef long long ll;
	mint(ll x = 0) :x((x% mod + mod) % mod) {}
	mint operator-() const { return mint(-x); }
	mint& operator+=(const mint a) {
		if ((x += a.x) >= mod) x -= mod;
		return *this;
	}
	mint& operator-=(const mint a) {
		if ((x += mod - a.x) >= mod) x -= mod;
		return *this;
	}
	mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this; }
	mint operator+(const mint a) const { return mint(*this) += a; }
	mint operator-(const mint a) const { return mint(*this) -= a; }
	mint operator*(const mint a) const { return mint(*this) *= a; }
	mint pow(ll t) const {
		if (!t) return 1;
		mint a = pow(t >> 1);
		a *= a;
		if (t & 1) a *= *this;
		return a;
	}

	// for prime mod
	mint inv() const { return pow(mod - 2); }
	mint& operator/=(const mint a) { return *this *= a.inv(); }
	mint operator/(const mint a) const { return mint(*this) /= a; }
};
istream& operator>>(istream& is, const mint& a) { return is >> a.x; }
ostream& operator<<(ostream& os, const mint& a) { return os << a.x; }

struct combination {
	vector<mint> fact, ifact;
	combination(int n) :fact(n + 1), ifact(n + 1) {
		fact[0] = 1;
		for (int i = 1; i <= n; ++i) fact[i] = fact[i - 1] * i;
		ifact[n] = fact[n].inv();
		for (int i = n; i >= 1; --i) ifact[i - 1] = ifact[i] * i;
	}
	mint operator()(int n, int k) {
		if (k < 0 || k > n) return 0;
		return fact[n] * ifact[k] * ifact[n - k];
	}
} comb(2000005);

mint g(int r, int c) {
	return comb(r + c + 2, r + 1) - 1;
}

bool comp(int i, int j) {
	return i > j;
}

long long plusL[100000];
long long plusR[100000];
long long minusL[100000];
long long minusR[100000];
long long a[100000];

int main()
{
	int n;
	cin >> n;
	int p[20];
	
	for (int i = 0; i < n; i++)
	{
		cin >> p[i];
	}
	
	int count = 0;
	for (int i = 1; i < n - 1; i++)
	{
		if (p[i - 1] < p[i] && p[i] < p[i + 1])
		{
			count++;
		}
		if (p[i - 1] > p[i] && p[i] > p[i + 1])
		{
			count++;
		}
	}
	cout << count;
}
//  [cpp]
#include <bits/stdc++.h>
#define pb push_back
#define Int long long
using namespace std;

const int MAXN=500005;
const long MOD=(long)(1e9+7);
vector<int> adj[MAXN];
vector<pair<int,int>> G[MAXN];

Int N,M,K;
Int B,C,H,W;
Int X,Y,Z;
vector<Int> A;

Int ceilS(Int x,Int y){
    return (x+y-1)/y;
}
using D=long double;

Int perform(Int x){
    return (x*(x+1))/2LL;
}

int main()
{
     cin>>N;
     A.resize(N);
     
     for(auto &x:A) cin>>x;
     Int ans=0;
     for(int i=1;i+1<N;++i){
         vector<Int> inner;
         for(int j=i-1;j<=i+1;++j) inner.pb(A[j]);
         sort(inner.begin(),inner.end());
         ans+=(inner[1]==A[i]);
     }
     cout<<ans<<"\n";
     
}
//  [cpp]
#include<bits/stdc++.h>
#define MIN -1000000
using namespace std;
typedef long long ll;
int p[25];
int main(void)
{
  int n;
  cin >> n;
  int ans=0;
  for(int i=0;i<n;i++)
  {
    cin >> p[i];
  }
  for(int i=1;i<n-1;i++)
  {
    if((p[i]>p[i-1] && p[i]<p[i+1]) || (p[i]>p[i+1] && p[i]<p[i-1]) ) ans++;
  }
  cout << ans << endl;
  return 0;
}
//  [c]
#include <stdio.h>

int main()
{
	int i, n, p[21], count = 0;
	scanf("%d", &n);
	for (i = 1; i <= n; i++) scanf("%d", &(p[i]));
	for (i = 2; i < n; i++) if ((p[i] - p[i-1]) * (p[i+1] - p[i]) > 0) count++;
	printf("%d\n", count);
	fflush(stdout);
	return 0;
}
//  [c]
#include<stdio.h>

main()

{
    int i, n, mehrab=0;
    scanf("%d",&n);

    int p[n];

    for(i=0; i<n; i++)
    {
        scanf("%d",&p[i]);
    }

    for(i=0; i<n-2; i++)
    {
        if((p[i+1]>p[i] && p[i+1]<p[i+2]) || (p[i+1]<p[i] && p[i+1]>p[i+2]))
        {
            mehrab++;
        }
    }

    printf("%d\n",mehrab);

    return 0;
}
//  [c]
#include<stdio.h>
int main()
{
    int a[100],n,c=0,b=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(int i=1;i<n-1;i++)
    {
        if(a[i-1]>a[i] && a[i+1]>a[i])
        {
            b++;
        }
        else if(a[i-1]<a[i] && a[i+1]<a[i])
        {
            b++;
        }
        else
        {
            c++;
        }
    }
    printf("%d",c);


}
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0]);
    const p = arg[1].split(" ").map(n=>parseInt(n));
    
    let answer = 0;
    
    for(let i=0; i<N-2; i++) {
        let left   = p[i];
        let middle = p[parseInt(i) + 1];
        let right  = p[parseInt(i) + 2];
        
        let array = [left, middle, right].sort((a,b)=>a-b);
        
        if(array[1] === middle) {
            answer++;
        }
    }
    
    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
'use strict'

const main = (INPUT) => {
  const input = INPUT.split('\n')
  const n = Number(input[0])
  const p = input[1].split(' ').map(n => Number(n))
  let ans = 0
  for (let i = 1; i < p.length - 1; i++) {
    if (p[i - 1] <= p[i] && p[i] <= p[i + 1] || p[i - 1] >= p[i] && p[i] >= p[i + 1]) {
      ans++
    }
  }
  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
function Main(input) {
  lines = input.split("\n")
  N = lines[0] * 1
  s = lines[1].split(" ").map(function(i) { return i * 1})
  cnt = 0
  for (var i = 0; i < s.length - 2; i++) {
    t = s.slice(i, i + 3)
    t = t.sort(function(a, b) { return a - b })
    if (t[1] == s[i+1]) {
      cnt++
    }
  }
  console.log(cnt)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"fmt"
)

func main() {

	var n int
	fmt.Scanf("%d", &n)

	p := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &p[i])
	}

	var count int = 0
	for i := 1; i < n-1; i++ {
		if (p[i-1] <= p[i] && p[i] <= p[i+1]) || (p[i-1] >= p[i] && p[i] >= p[i+1]) {
			count++
		}
	}

	fmt.Println(count)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)

	n := nextInt()
	plist := make([]int, n)
	for i := 0; i < n; i++ {
		plist[i] = nextInt()
	}

	cnt := 0
	for i := 1; i < n-1; i++ {
		if plist[i-1] <= plist[i] && plist[i] <= plist[i+1] {
			cnt++
		} else if plist[i-1] >= plist[i] && plist[i] >= plist[i+1] {
			cnt++
		}

	}

	fmt.Println(cnt)
}

// ---- readfunc
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
func nextIntMat(a int, b int) [][]int {
	mat := make([][]int, a)
	for i := 0; i < a; i++ {
		mat[i] = make([]int, b)
		for j := 0; j < b; j++ {
			mat[i][j] = nextInt()
		}
	}
	return mat
}
//  [go]
package main

import (
  "fmt"
)

func main() {
  var n int
  fmt.Scanf("%v", &n)
  var p []int
  for i:=0;i<n;i++ {
    pp := 0
    fmt.Scanf("%v", &pp)
    p = append(p, pp)
  }
  sum := 0
  for i:=0;i<n-2;i++ {
    if (p[i]<p[i+1] && p[i+1]<p[i+2]) || (p[i]>p[i+1] && p[i+1]>p[i+2]) {
      sum ++
    }
  }
  fmt.Println(sum)
}
//  [ruby]
_,*a=`dd`.split.map &:to_i
c=0
a.each_cons(3) do |n|
  c+=1 if n[1]==n.sort[1]
end
p c
//  [ruby]
input = readlines()

n = input.shift.chomp.to_i
list = input.shift.chomp.split("\s").map{|x| x.to_i}

cnt = 0
list.each_with_index do |l, i|
  next if i < 2
  tmp = [list[i - 2], list[i - 1], l].sort()
  cnt += 1 if tmp[1] == list[i - 1]
end

puts cnt
//  [ruby]
n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
cnt = 0
1.upto(n-2) do |i|
	ar = arr.slice(i-1,3)
	cnt += 1 if ar.max > arr[i] && ar.min < arr[i]
end
puts cnt
//  [rust]
#![allow(non_snake_case)]
#![allow(unused_imports)]
use proconio::input;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::VecDeque;

fn main() {
    input! {
        N: usize,
        Ps: [i64; N],
    }

    let mut ans = 0;
    for i in 2..N {
        if (Ps[i - 2] < Ps[i - 1] && Ps[i - 1] < Ps[i])
            || (Ps[i] < Ps[i - 1] && Ps[i - 1] < Ps[i - 2])
        {
            ans += 1;
        }
    }

    println!("{}", ans);
}
//  [rust]
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use {
    proconio::{marker::*, *},
    std::{cmp::*, collections::*, mem::*},
};

#[fastout]
fn main() {
    input! {//
        n:usize,
        a:[i64;n],
    }
    let mut ans = 0;
    for i in 1..n - 1 {
        let mut left = min(a[i - 1], a[i + 1]);
        let mut right = max(a[i - 1], a[i + 1]);
        if (left..right).contains(&a[i]) {
            ans += 1;
        }
    }
    println!("{}", ans);
}
//  [rust]
#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n = read::<usize>();
    let p = read_vec::<usize>();
    let mut ans = 0;
    for j in 1..n - 1 {
        let i = j - 1;
        let k = j + 1;
        if (p[i] > p[j] && p[j] > p[k]) || p[i] < p[j] && p[j] < p[k] {
            ans += 1;
        }
    }
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}
//  [swift]
import Foundation
 
let input_line = readLine()!
 
let split = input_line.componentsSeparatedByString(" ") //components(separatedBy:)と実質同じ
let N = Int(input_line)!
 
var Pi = [Int]()
let input_line2 = readLine()!

let splits = input_line2.componentsSeparatedByString(" ") //components(separatedBy:)と実質同じ
Pi = splits.map {Int($0)!}

var counter = 0

for i in 0..<N - 2 {
    if Pi[i] < Pi[i + 1] && Pi[i + 1] < Pi[i + 2] {
        counter += 1
    } else if Pi[i + 2] < Pi[i + 1] && Pi[i + 1] < Pi[i] {
        counter += 1
    }
}
print(counter)
//  [swift]
let n = Int(readLine()!)!
let p = readLine()!.characters.split(" ").map{Int(String($0))!}
print((1..<n-1).reduce(0){i,j in let k=(p[j-1]<p[j]&&p[j]<p[j+1])||(p[j-1]>p[j]&&p[j]>p[j+1]) ?1:0;return i+k})
//  [swift]
let n = Int(readLine()!)!
let p = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 1..<n-1 {
    let arr = [p[i-1], p[i], p[i+1]].sort()
    if p[i] == arr[1] {
        ans += 1
    }
}
print(ans)