	import java.io.*;
	import java.math.BigInteger;
	import java.util.*;
import java.util.Map.Entry;

	public class Main
	{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;
		private PrintWriter pw;
		private long mod = 1000000000 + 7;

		private StringBuilder ans_sb;
		private int block;

		private void soln()
		{
			int t = nextInt();
			while(t-- > 0) {
				int n = nextInt();
				int k = nextInt();
				int max = 0;
				int prev = 0;
				for(int i=0;i<k;i++) {
					int x = nextInt();
					if(prev == 0)
						max = Math.max(max, (x - prev));
					else {
						if((x- prev + 1)%2!=0)
							max = Math.max(max, (x - prev + 1)/2 + 1);
						else
							max = Math.max(max, (x - prev + 1)/2);
					}
			//		debug(max);
					prev = x;
				}
				max = Math.max(max, n+1 - prev);
				pw.println(max);
			}
				/*int n = nextInt();
				Student[] ss = new Student[n];
				for(int i=0;i<n;i++) {
					ss[i] = new Student(nextInt(),nextInt(),i);
				}
			//	Arrays.sort(ss);
				int time = 1;
				int[] ans = new int[n];
				for(int i=0;i<n;i++) {
					Student tmp = ss[i];
					time = Math.max(time, tmp.l);
					if(time > tmp.r) {
						ans[tmp.i] = 0;
					}else {
						ans[tmp.i] = time;
						time++;
					}
				}
				for(int i=0;i<n;i++)
					pw.print(ans[i]+" ");
				pw.println();
			}*/
		/*	int n = nextInt();
			int[] arr = nextIntArray(n);
			Merge sort = new Merge();
			int[] tmp = arr.clone();
			sort.sort(tmp);
		//	debug(tmp);
			String s = nextLine();
			boolean f = true;
		//	ArrayList<HashSet> l = new ArrayList<>();
			HashSet<Integer> set1 = new HashSet<>();
			HashSet<Integer> set2 = new HashSet<>();
			for(int i=0;i<s.length();i++) {
				if(s.charAt(i)=='0') {
					set1.add(arr[i]);
					set2.add(tmp[i]);
				//	debug(set1);
				//	debug(set2);
				//	l.add(set1);
					if(set1.size() != set2.size()) {
						f=false;
						break;
					}else {
						for(int x: set1) {
							if(!set2.contains(x)) {
								f=false;
								break;
							}
						}
						if(!f)
							break;
					}
					set1 = new HashSet<>();
					set2 = new HashSet<>();
				}else {
					set1.add(arr[i]);
					set2.add(tmp[i]);
				}
			}
			for(int i=s.length();i<n;i++) {
				set1.add(arr[i]);
				set2.add(tmp[i]);
			}
			if(set1.size() != set2.size()) {
				f=false;
			}else {
				for(int x: set1) {
					if(!set2.contains(x)) {
						f=false;
						break;
					}
				}
			}
			if(f)
				pw.println("YES");
			else
				pw.println("NO");*/
		}

private class Student implements Comparable<Student>{
	int l,r,i;
	public Student(int a,int b,int c) {
		l=a;
		r=b;
		i=c;
	}
	@Override
	public int compareTo(Student arg0)
	{
		if(this.l != arg0.l)
			return this.l - arg0.l;
		else
			return this.i - arg0.i;
	}
}
public class Merge {
	public void sort(int inputArr[]) {
        int length = inputArr.length;
        doMergeSort(inputArr,0, length - 1);
    }
    private void doMergeSort(int[] arr,int lowerIndex, int higherIndex) {
        if (lowerIndex < higherIndex) {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            doMergeSort(arr,lowerIndex, middle);
            doMergeSort(arr,middle + 1, higherIndex);
            mergeParts(arr,lowerIndex, middle, higherIndex);
        }
    }
    private void mergeParts(int[]array,int lowerIndex, int middle, int higherIndex) {
    	int[] temp=new int[higherIndex-lowerIndex+1];
        for (int i = lowerIndex; i <= higherIndex; i++) {
            temp[i-lowerIndex] = array[i];
        }
        int i = lowerIndex;
        int j = middle + 1;
        int k = lowerIndex;
        while (i <= middle && j <= higherIndex) {
            if (temp[i-lowerIndex] < temp[j-lowerIndex]) {
                array[k] = temp[i-lowerIndex];
                i++;
            } else {
                array[k] = temp[j-lowerIndex];
                j++;
                //cnt+=(middle+1-i);
            }
            k++;
        }
        while (i <= middle) {
            array[k] = temp[i-lowerIndex];
            k++;
            i++;
        }
        while(j<=higherIndex){
        	array[k]=temp[j-lowerIndex];
        	k++;
        	j++;
        }
        /*pw.println(lowerIndex+" "+higherIndex);
        for(int m=lowerIndex;m<=higherIndex;m++)
        	pw.print(array[m]+" ");
        pw.println();*/
    }
}

		private String solveEqn(long a, long b) {
	        long x = 0, y = 1, lastx = 1, lasty = 0, temp;
	        while (b != 0){
	        	long q = a / b;
	        	long r = a % b;
	            a = b;
	            b = r;
	            temp = x;
	            x = lastx - q * x;
	            lastx = temp;
	            temp = y;
	            y = lasty - q * y;
	            lasty = temp;
	        }
	        return lastx+" "+lasty;
		}
		private void debug(Object... o) {
			System.out.println(Arrays.deepToString(o));
		}

		private long pow(long a, long b, long c)
		{
			if (b == 0)
				return 1;
			long p = pow(a, b / 2, c);
			p = (p * p) % c;
			return (b % 2 == 0) ? p : (a * p) % c;
		}

		private long gcd(long n, long l)
		{
			if (l == 0)
				return n;
			return gcd(l, n % l);
		}
		public static void main(String[] args) throws Exception
		{
			/*new Thread(null, new Runnable()
			{
				@Override
				public void run()
				{
					new Main().solve();
				}
			}, "1", 1 << 25).start();*/
			new Main().solve();
		}
		public StringBuilder solve(){
			InputReader(System.in);
			/*try {
				InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
			} catch(FileNotFoundException e) {}
			*/
			pw = new PrintWriter(System.out);
			//ans_sb = new StringBuilder();
			soln();

			pw.close();
			//System.out.println(ans_sb);
			return ans_sb;
		}
		public void InputReader(InputStream stream1)
		{
			stream = stream1;
		}

		private boolean isWhitespace(int c)
		{
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c)
		{
			return c == '\n' || c == '\r' || c == -1;
		}

		private int read()
		{
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars)
			{
				curChar = 0;
				try
				{
					numChars = stream.read(buf);
				} catch (IOException e)
				{
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		private int nextInt()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			int res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		private long nextLong()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			long res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		private String nextToken()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		private String nextLine()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		private int[] nextIntArray(int n)
		{
			int[] arr = new int[n];
			for (int i = 0; i < n; i++)
			{
				arr[i] = nextInt();
			}
			return arr;
		}

		private long[] nextLongArray(int n)
		{
			long[] arr = new long[n];
			for (int i = 0; i < n; i++)
			{
				arr[i] = nextLong();
			}
			return arr;
		}

		private void pArray(int[] arr)
		{
			for (int i = 0; i < arr.length; i++)
			{
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			return;
		}

		private void pArray(long[] arr)
		{
			for (int i = 0; i < arr.length; i++)
			{
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			return;
		}

		private boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return isWhitespace(c);
		}

		private char nextChar()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			char c1 = (char) c;
			while (!isSpaceChar(c))
				c = read();
			return c1;
		}

		private interface SpaceCharFilter
		{
			public boolean isSpaceChar(int ch);
		}
	}

t=int(input())
for _ in range(t):
    n,k=list(map(int,input().split()))
    x=list(map(int,input().split()))
    b=[]
    for i in range(1,n+1):
        a=[]
        for j in range(k):
            a.append(abs(x[j]-i))
        b.append(min(a))
    print(max(b)+1)


import java.util.Scanner;

public class P736B
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		if (prime(n))
			System.out.println(1);
		else if (n % 2 == 0 || prime(n - 2))
			System.out.println(2);
		else
			System.out.println(3);
		in.close();
	}

	public static boolean prime(int n)
	{
		for (int i = 2; i * i <= n; i++)
			if (n % i == 0)
				return false;
		return true;
	}
}

#include <bits/stdc++.h>
using namespace std;
long long prime(long long n) {
  for (long long i = 2; i * i <= n; ++i)
    if (n % i == 0) return 0;
  return 1;
}
signed main() {
  ios_base::sync_with_stdio(0);
  long long n;
  cin >> n;
  if (prime(n))
    cout << 1;
  else if (n % 2 == 0)
    cout << 2;
  else if (prime(n - 2))
    cout << 2;
  else
    cout << 3;
  return 0;
}


n = int(input())
l = list(map(int, input().split()))

r = 0
par = []
nep = []

for item in l:
    if item % 2 == 0:
        par.append(item)

    else:
        nep.append(item)

if len(nep) % 2 == 0 and nep != []:
    nep.remove(min(nep))

r += sum(nep)

if r != 0:
    r += sum(par)

print(r)

#include <bits/stdc++.h>
using namespace std;
int n, sum;
bool error;
vector<int> oddvec, evenvec;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    int xs;
    cin >> xs;
    sum += xs;
    if (xs & 1)
      oddvec.push_back(xs);
    else
      evenvec.push_back(xs);
  }
  sort(oddvec.begin(), oddvec.end());
  sort(evenvec.begin(), evenvec.end());
  if (sum % 2 == 0) {
    if (!oddvec.size())
      error = true;
    else
      sum -= oddvec[0];
  }
  if (!error)
    cout << sum << "\n";
  else
    cout << 0 << "\n";
  return 0;
}


import java.io.*;
import java.util.*;
public class CF_476D {
    public static void main(String[] args) throws IOException {
        new CF_476D().solve();
    }

    void solve() throws IOException{

        InputStream in = System.in;
        PrintStream out = System.out;

//        in = new FileInputStream("in.txt");
//        out = new PrintStream("out.txt");

        Scanner sc=new Scanner(in);
        int n=sc.nextInt(), k=sc.nextInt();

        int max=0;
        StringBuilder ans=new StringBuilder();
        for (int i=0;i<n;i++){
            ans.append(k*(6*i+1)+" "+k*(6*i+2)+" "+k*(6*i+3)+" "+k*(6*i+5)+"\n");
            max=k*(6*i+5);
        }
        out.println(max);
        out.println(ans.toString());

    }
}

a, b = map(int, input().split(' '))

print((6*a-1)*b)

for i in range(a):

    print((6*i+1)*b, (6*i+2)*b, (6*i+3)*b, (6*i+5)*b)

# Made By Mostafa_Khaled


n = int(input())
a = [0]*(10**5 + 1)
c = []
for i in range(n):
    x,y = map(int, input().split())
    c.append([x,y])
    a[x]+=1
ans = n - 1
for i in range(n):
    d = ans + a[c[i][1]]
    print(d,2*(n - 1) - d)

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2 * 100000 + 10, MOD = 1000 * 1000 * 1000 + 7,
          INF = 1000 * 1000 * 1000;
const double EPS = 1e-9, PI = 2. * acos(0.0);
int first[maxn];
pair<int, int> kit[maxn];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> kit[i].first >> kit[i].second;
    first[kit[i].first]++;
  }
  for (int i = 0; i < n; ++i) {
    int home = first[kit[i].second] + n - 1;
    cout << home << ' ' << 2 * (n - 1) - home << endl;
  }
  return 0;
}


import java.util.Arrays;
import java.util.Scanner;

public class NearlyLuckyNumber {
    public static void main(String[] args) {
        Scanner lol = new Scanner(System.in);
       int n = lol.nextInt();
       int ans[] = new int[n];
       for(int i=0;i<n;i++){
           ans[i]=lol.nextInt();
       }
       Arrays.sort(ans);
       for(int i=0;i<n;i++){
           System.out.print(ans[i]+" ");
       }
    }
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  int arr[105];
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  sort(arr, arr + n);
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}


n,m,k = map(int,input().split())
for i in range(n):
    a = [int(x) for x in input().split()]
d = []
for i in range(1,m):
	for j in range(i+1,m+1):
		if k == 0:
			d.append((i,j))
		else:
			d.append((j,i))
print(len(d))
for i in d:
	print(*i)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, k, i, j;
  cin >> n >> m >> k;
  cout << m * (m - 1) / 2 << endl;
  if (k) {
    for (i = 1; i < m; i++)
      for (j = i + 1; j <= m; j++) cout << j << " " << i << endl;
  } else {
    for (i = 1; i < m; i++)
      for (j = i + 1; j <= m; j++) cout << i << " " << j << endl;
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int n, m, i, j, a[1001], b[1001], c[1001], mi = 0, ma = 0;
  cin >> n >> m;
  for (i = 0; i < m; i++) cin >> a[i], b[i] = c[i] = a[i];
  sort(b, b + m);
  sort(c, c + m, greater<int>());
  i = 0, j = n;
  while (j) {
    ma += c[0];
    c[0]--;
    sort(c, c + m, greater<int>());
    j--;
  }
  i = 0, j = n;
  while (j) {
    while (b[i] && j) {
      mi += b[i];
      b[i]--;
      j--;
    }
    i++;
  }
  cout << ma << " " << mi << '\n';
  return 0;
}

n,m=list(map(int,input().split()))
L=list(map(int,input().split()))
P=list(map(int,L))

mi=0
ma=0

for i in range(n):
    x=max(L)
    ma+=x
    L[L.index(x)]-=1

#print(P)
for i in range(n):
    x=min(P)
    if x==0:
        P.remove(x)
    x=min(P)
    mi+=x
    P[P.index(x)]-=1

print(ma,mi)


#include <bits/stdc++.h>
using namespace std;
double a[100];
int main() {
  int n;
  double b, sum, m = 0, one;
  cin >> n >> b;
  sum = b;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
    m = max(m, a[i]);
  }
  one = sum / n;
  if (m > one) {
    cout << -1;
    return 0;
  }
  for (int i = 0; i < n; i++) printf("%0.9lf\n", -a[i] + one);
}

a,b=map(int,input().split())
l=list(map(int,input().split()))
if (max(l)*a)-sum(l)>b:
    print(-1)
else:
    for i in l:
        print((sum(l)+b)/a-i)


#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e5 + 10;
long long N, arr[maxn];
signed main() {
  ios::sync_with_stdio(false);
  cin >> N;
  set<long long> st, today;
  vector<long long> v;
  long long h = 1;
  for (register long long i = 1; i <= N; ++i) {
    cin >> arr[i];
    if (arr[i] < 0) {
      if (st.count(-arr[i])) {
        st.erase(-arr[i]);
      } else {
        cout << "-1" << endl;
        return 0;
      }
      if (st.size() == 0) {
        v.push_back(i - h + 1);
        today.clear();
        h = i + 1;
      }
    } else {
      if (today.count(arr[i])) {
        cout << "-1" << endl;
        return 0;
      }
      st.insert(arr[i]);
      today.insert(arr[i]);
    }
  }
  if (st.size() != 0) {
    cout << -1 << endl;
    return 0;
  }
  cout << v.size() << endl;
  for (auto i : v) {
    cout << i << " ";
  }
  return 0;
}


import java.util.Scanner;
public class CodeForces {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
	int n = sc.nextInt();
	int k = sc.nextInt();
        int[] a = new int[k];
        for (int i = 0; i < n; i++) {
            a[sc.nextInt()-1]++;
        }
        int ans = 0;
        for (int i = 0; i < k; i++) {
            if (a[i] % 2 == 1) {
                ans++;
            }
        }
        if (n%2==1) {
            ans--;
        }
        ans/=2;
        System.out.println(n-ans);
    }
}

from math import  ceil

n, k = map(int, input().split())
bev = [0] * k
for i in range(n):
    x = int(input())
    bev[x-1] += 1

bad = 0
good = 0
for i in range(k):
    bad += bev[i] & 1
    good += bev[i] - (bev[i] & 1)
# print(good, bad)
bad = ceil(bad / 2)
print(good + bad)


import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        int b = scn.nextInt();
        int a = scn.nextInt();
        int in = a;
        int count =0;
        for(int i=1;i<=n;++i){

            int temp = scn.nextInt();
            if(temp == 0){
                if(a-1>=0){
                   a--;
                   count++;
                }else if(b-1>=0){
                    b--;
                    count++;
                }else{
                    break;
                }
            }else{
                if(b-1>=0||in==0){
                  if(a+1<=in){
                   b--;
                   a++;
                  }else{
                      a--;
                  }
                   count++;
                }else if(a-1>=0){
                    a--;
                    count++;
                }else{
                    break;
                }
            }
            // System.out.println(b+" "+a);
            }
            System.out.println(count);

    }
}

n,b,a=map(int,input().split())
s=list(map(int,input().split()))
maxa=a
cnt=0
for i in range(n):
	if(s[i]==0):
		if(a>0):
			a-=1
			cnt+=1
		elif(b>0):
			b-=1
			cnt+=1
	else:
		if(a<maxa and b>0):
			b-=1
			a+=1
			cnt+=1
		elif(a>0):
			a-=1
			cnt+=1
	if(b==0 and a==0):
		break
print(cnt)


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m;
  cin >> n >> m;
  cout << max(0LL, n - m * 2) << " ";
  for (long long i = 0; i <= n; i++) {
    if (i * (i - 1) / 2 >= m) {
      cout << n - i;
      return 0;
    }
  }
  cout << 0;
}

import java.util.Scanner;

public class CF1065B {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        long n = scanner.nextInt();
        long m = scanner.nextLong();

        double denseVertexes = Math.ceil((Math.sqrt(8 * m + 1) + 1) / 2);
        long denseVertexes1 = (long) denseVertexes;
        long max = n - (denseVertexes1 == 1 ? 0 : denseVertexes1);
        long min = n > 2 * m ? n - 2 * m : 0;
        System.out.println(String.format("%d %d", min, max));
    }
}


n = int(input())
l = '0' + input() +'0'
o = 0
z = 0
flag = True
for i in l:
    if i == "0" and z < 2:
        z += 1
        o = 0
    elif i == "1" and o != 1:
        o = 1
        z = 0
    else:
        flag = False
        break
if flag:
    print("Yes")
else:
    print("No")

Yes No No No No No No No No Yes No No No Yes No Yes No No No No No No No No No No No Yes No Yes No No No No Yes No No No No No No Yes Yes No Yes No No No No No No No Yes No Yes No No No No No No No Yes No No No No No No No Yes No No Yes No No No No Yes No No No No No No No


def complete_canvas(s):
    double = False
    res = ""
    for i,c in enumerate(s):
        if i>0 and i<len(s)-1 and c=='?' and s[i-1] in colors and s[i+1] in colors:
            #and s[i-1]!=s[i+1]
            col = list(colors)
            col.remove(s[i-1])
            if s[i-1]!=s[i+1]:
                col.remove(s[i+1])
            if s[i-1]==s[i+1]:
                double = True
            res += col[0]
        else:
            res += c
    return res, double

def is_valid(s):
    for i,c in enumerate(s):
        if i>0 and c!='?' and c==s[i-1]:
            return False
    return True

def consecutive_undef(s):
    for i,c in enumerate(s):
        if i>0 and c=='?' and c==s[i-1]:
            return True
    return False

def is_complete(s):
    return not "?" in s

def extreme_undef(s):
    if s[0]=='?' or s[-1]=='?':
        return True
    return False

import sys
n = int(input())
s = input()
if is_complete(s) or not is_valid(s):
    print("No")
    sys.exit()

possible = set()
colors = set(["M","Y","C"])

if consecutive_undef(s):
    print("Yes")
    sys.exit()

if extreme_undef(s):
    print("Yes")
    sys.exit()

s, double = complete_canvas(s)
if double:
    print("Yes")
    sys.exit()
else:
    print("No")
    sys.exit()

No Yes No No No No No No No Yes Yes No No Yes No No No Yes No No No No Yes No Yes Yes No No No Yes No No Yes No No Yes Yes No No No Yes Yes No Yes Yes No No No No Yes


import java.util.Scanner;
import java.lang.String;
import java.lang.Math;
 import java.util.Arrays;
 import java.util.Collections;

public class Olymp {

 private static Scanner ob;

 public static void main(String[] args){
  ob = new Scanner(System.in);
  int a=ob.nextInt();
  if (a==1) System.out.print("23:59");
  else {
      String b;
      int[] my  = new int[a];
      for (int i = 0; i< a;i++){
        b =ob.next();
        int time  =  Character.getNumericValue(b.charAt(0))*60*10  +  Character.getNumericValue(b.charAt(1))*60 +  Character.getNumericValue(b.charAt(3))*10 +  Character.getNumericValue(b.charAt(4));
        my[i] = time;
      }
      Arrays.sort(my);
      int[] my2  = new int[a];
      for (int i = 1;i<a;i++){
          my2[i] = my[i] - my[i-1] -1;
      }

      my2[0] = my[0] + 24*60 - my[a-1] -1;

    Arrays.sort(my2);
    int all = my2[a-1];
      int h1 = all/600;
      all = all - h1*600;
      int h2 = all/60;
      all = all - h2*60;
      int m1 = all/10;
      all = all  - m1*10;
      System.out.print(h1);
            System.out.print(h2);
      System.out.print(":");
      System.out.print(m1);
      System.out.print(all);

  }

  }
}


def banyak_tahun(a,b, count):
    c = a*3
    d = b*2
    if c <= d:
        banyak_tahun(c,d, count+1)
    else:
        print(count)

a, b = list(map(int, input().split()))
banyak_tahun(a,b,1)

#include <bits/stdc++.h>
using namespace std;
int a, b;
int y = 0;
int main() {
  cin >> a >> b;
  while (a <= b) {
    a = a * 3;
    b = b * 2;
    y++;
  }
  cout << y;
  return 0;
}


import java.io.*;
import java.util.*;

public class B {
	FastScanner in;
	PrintWriter out;

	void solve() {
		long start = in.nextLong();
		long end = in.nextLong();
		long t = in.nextLong();
		int n = in.nextInt();
		long bestT = start;
		long result = 0;
		long firstEmpty = start;
		for (int i = 0; i < n; i++) {
			long curT = in.nextLong();
			long need = Math.min(firstEmpty, curT - 1);
			if (firstEmpty - need <= bestT) {
				bestT = firstEmpty - need;
				result = need;
			}
			firstEmpty = Math.max(firstEmpty, curT) + t;
			if (firstEmpty + t > end) {
				break;
			}
		}
		if (firstEmpty + t <= end) {
			result = firstEmpty;
		}
		out.println(result);
	}

	void run() {
		try {
			in = new FastScanner(new File("object.in"));
			out = new PrintWriter(new File("object.out"));

			solve();

			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	void runIO() {

		in = new FastScanner(System.in);
		out = new PrintWriter(System.out);

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (s == null)
					return null;
				st = new StringTokenizer(s);
			}
			return st.nextToken();
		}

		boolean hasMoreTokens() {
			while (st == null || !st.hasMoreTokens()) {
				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (s == null)
					return false;
				st = new StringTokenizer(s);
			}
			return true;
		}

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

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}
	}

	public static void main(String[] args) {
		new B().runIO();
	}
}

##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))

[ts , tf, t] = list(map(int, input().split()))

n = int(input())
if n == 0:
    print(ts)
    exit(0)

a = list(map(int, input().split()))
if a[0] > ts:
    print(ts)
    exit(0)

min_wait = 1e18
tbest = a[0]-1
tnow = ts
twait = tnow-tbest
min_wait = min(min_wait, twait)

i = 0
while i < n:
    tnow = max(tnow, a[i])
    j = i
    while j < n and a[j] == a[i]:
        j += 1
    tnow += (j-i)*t
    if j == n:
        break
    tcome = a[j]-1
    twait = tnow-tcome
    if twait < min_wait and tcome+t <= tf:
        min_wait = twait
        tbest = tcome
    i = j

if tnow+t <= tf:
    print(tnow)
else:
    print(tbest)


#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  int n, a[105];
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  string t;
  getline(cin, t);
  for (int ii = 1; ii <= n; ii++) {
    string s;
    getline(cin, s);
    int m = s.length(), c = 0;
    for (int i = 0; i <= m - 1; i++) {
      if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' ||
          s[i] == 'u' || s[i] == 'y')
        c++;
    }
    if (c != a[ii]) {
      cout << "NO";
      return 0;
    }
  }
  cout << "YES";
  return 0;
}

5
2 11 10 7 9
hy of
yur pjyacbatdoylojayu
emd ibweioiimyxya
yocpyivudobua
uiraueect impxqhzpty e

4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles

5
0 10 6 6 0
fgthrxst
sohnweymewnnmbobj
j
fwwt acdtfvkpv khbxokn
hndovkkgfhnhqod

2
26 35
gouojxaoobw iu bkaadyo degnjkubeabt kbap thwki dyebailrhnoh ooa
piaeaebaocptyswuc wezesazipu osebhaonouygasjrciyiqaejtqsioubiuakg umynbsvw xpfqdwxo

import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
import static java.lang.Math.*;

// Sachin_2961 submission //
public class CodeforcesA {

    public boolean isVowel(char c){
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y';
    }
    public void solve() {
        int n = fs.nInt();
        int[]ar = new int[n];
        for(int i=0;i<n;i++)
            ar[i] = fs.nInt();

        String[]s = new String[n];
        for(int i=0;i<n;i++){
            s[i] = fs.Line();
        }
        for(int i=0;i<n;i++){
            int cnt = 0;
            for(int j=0;j<s[i].length();j++){
                if( isVowel(s[i].charAt(j)))
                    cnt++;
            }
            if(cnt != ar[i]){
                out.println("NO");return;
            }
        }
        out.println("YES");
    }

    static boolean multipleTestCase = false; static FastScanner fs; static PrintWriter out;
    public void run(){
        fs = new FastScanner();
        out = new PrintWriter(System.out);
        int tc = (multipleTestCase)?fs.nInt():1;
        while (tc-->0)solve();
        out.flush();
        out.close();
    }
    public static void main(String[]args){
        try{
            new CodeforcesA().run();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String n() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }
        String Line()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        int nInt() {return Integer.parseInt(n()); }
        long nLong() {return Long.parseLong(n());}
        int[]aI(int n){
            int[]ar = new int[n];
            for(int i=0;i<n;i++)
                ar[i] = nInt();
            return ar;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k, i, h[100005], st = 1, ed, mid, cnt, a, b;
  multiset<int> s;
  scanf("%d %d", &n, &k);
  for (i = 0; i < n; i++) {
    scanf("%d", h + i);
  }
  ed = n;
  while (st <= ed) {
    mid = (st + ed) / 2;
    cnt = 0;
    s.clear();
    for (i = 0; i < mid - 1; i++) {
      s.insert(h[i]);
    }
    for (; i < n; i++) {
      s.insert(h[i]);
      if (*s.rbegin() - *s.begin() <= k) {
        cnt++;
      }
      s.erase(s.find(h[i - mid + 1]));
    }
    if (cnt) {
      a = mid;
      b = cnt;
      st = mid + 1;
    } else {
      ed = mid - 1;
    }
  }
  printf("%d %d\n", a, b);
  s.clear();
  for (i = 0; i < a - 1; i++) {
    s.insert(h[i]);
  }
  for (; i < n; i++) {
    s.insert(h[i]);
    if (*s.rbegin() - *s.begin() <= k) {
      printf("%d %d\n", i - a + 2, i + 1);
    }
    s.erase(s.find(h[i - a + 1]));
  }
}

from collections import deque
def mini_in_window(A, n, k):
    d = deque()
    res = []
    for i in range(n):
        if i >= k and d[0] == i - k:
            d.popleft()
        while len(d) and A[d[-1]] >= A[i]:
            d.pop()
        d.append(i)
        if i >= k - 1:
            res.append(d[0])
    return res

def maxi_in_window(A, n, k):
    d = deque()
    res = []
    for i in range(n):
        if i >= k and d[0] == i - k:
            d.popleft()
        while len(d) and A[d[-1]] <= A[i]:
            d.pop()
        d.append(i)
        if i >= k - 1:
            res.append(d[0])
    return res

n, k = map(int, input().split())
A = list(map(int, input().split()))
l = 0
r = n + 1
maxans = 0
cntmax = []
while l + 1 < r:
    mid = (l + r) // 2
    if mid > maxans:
        cntnow = []
        mins = mini_in_window(A, n, mid)
        maxes = maxi_in_window(A, n, mid)
        for i in range(len(mins)):
            if A[maxes[i]] - A[mins[i]] <= k:
                cntnow.append((i + 1, mid + i))
        if cntnow:
            l = mid
            cntmax = cntnow[:]
        else:
            r = mid
print(l, len(cntmax))
for line in cntmax:
    print(' '.join(map(str, line)))


n = int(input())
a = [int(x) for x in input().split(" ")]
a.sort()

for i in range(n):
    if i%2 == 0:
        firval = a[i]
        secval = a[i-1]
        if i == 0:
            continue
        elif firval > secval:
            a[i],a[i-1] = a[i-1],a[i]
        elif secval >= firval:
            continue
    elif i%2 != 0:
        firval = a[i]
        secval = a[i-1]
        if firval < secval:
            a[i],a[i-1] = a[i-1],a[i]
        elif secval <= firval:
            continue
final = []
for k in a:
    final.append(str(k))
print(' '.join(final))


/**
 * Created by KamnaYadav on 1/19/2017.
 */
import java.util.*;
public class tennisTournament {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int numCandidate = sc.nextInt();
        int numBottles = sc.nextInt();
        int numTowels = sc.nextInt();
        int numCandidates = numCandidate;
        double currentRound= 0;
        int numCurrentRound = 0;
        int numTowelsTotal = 0, numBottlesTotal= 0;
        while(numCandidate > 1){
            currentRound = Math.sqrt(numCandidate);

            numCurrentRound = (int)(numCandidate  / 2* 2);
            numCandidate-= numCurrentRound/2;
            numBottlesTotal += numCurrentRound * numBottles + numCurrentRound/2;
        }
        System.out.println(numBottlesTotal);
        System.out.println(numTowels * numCandidates);

    }
}

#include <bits/stdc++.h>
int main() {
  int n, b, p;
  std::cin >> n >> b >> p;
  std::vector<int> need_b(n, 0);
  std::queue<int> queue;
  for (int i = 0; i < n; ++i) {
    queue.push(i);
  }
  int calc_b = 0;
  while (queue.size() > 1u) {
    int pow2 = 1;
    while (pow2 * 2 <= int(queue.size())) {
      pow2 *= 2;
    }
    pow2 /= 2;
    std::queue<int> q2;
    for (int k = 0; k < pow2; ++k) {
      int i = queue.front();
      queue.pop();
      int j = queue.front();
      queue.pop();
      need_b[i] += b;
      need_b[j] += b;
      calc_b += 1;
      q2.push(i);
    }
    while (!queue.empty()) {
      q2.push(queue.front());
      queue.pop();
    }
    queue = q2;
  }
  calc_b += std::accumulate(need_b.begin(), need_b.end(), 0LL);
  std::cout << calc_b << " " << p * n << std::endl;
  return 0;
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;

public class A {

	public static void main(String[] args) {
		try (final Scanner sc = new Scanner(System.in)) {

			final long a = sc.nextLong();
			final long b = sc.nextLong();
			final long c = sc.nextLong();

			final long x = sc.nextLong();
			final long y = sc.nextLong();
			final long z = sc.nextLong();

			final long less = Math.max(0, x - a) + Math.max(0, y - b) + Math.max(0, z - c);
			final long gens = Math.max(0, (a - x) / 2) + Math.max(0, (b - y) / 2) + Math.max(0, (c - z) / 2);
			//System.out.println(gens + " " + less);

			System.out.println(less <= gens ? "Yes" : "No");
		}
	}

	public static class Scanner implements Closeable {
		private BufferedReader br;
		private StringTokenizer tok;

		public Scanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		private void getLine() {
			try {
				while (!hasNext()) {
					tok = new StringTokenizer(br.readLine());
				}
			} catch (IOException e) { /* ignore */
			}
		}

		private boolean hasNext() {
			return tok != null && tok.hasMoreTokens();
		}

		public String next() {
			getLine();
			return tok.nextToken();
		}

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

		public long nextLong() {
			return Long.parseLong(next());
		}

		public void close() {
			try {
				br.close();
			} catch (IOException e) { /* ignore */
			}
		}
	}
}


import java.util.Scanner;

public class OlesyaRodion {

    public static void main(String[] args) {

        int n, t;
        String number = "";
        Scanner input = new Scanner(System.in);

        n = input.nextInt();
        t = input.nextInt();

        if((n == 1 && t == 10)) System.out.println(-1);

        else if(n > 1 && t == 10){
            for(int i = 0; i < n-1; i++){
                number += '1';
            }
                number += '0';

                System.out.println(number);
        }

        else{
            String temp = Integer.toString(t);
            for(int i = 0; i < n; i++){
                number += temp;
            }
            System.out.println(number);
        }

    }

}

n, t = input().split(' ')

n = int(n)
t = int(t)

a = 10 ** (n-1)
b = 10 ** (n)

for i in range(a, b):
    if i == b-1:
        if i%t ==0:
            print(i)
            break
        else:
            print(-1)
            break
    else:
        if i%t == 0:
            print(i)
            break

    i = i + 1


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author saket
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		PaintingPebbles solver = new PaintingPebbles();
		solver.solve(1, in, out);
		out.close();
	}
}

class PaintingPebbles {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n=in.readInt();
        int k=in.readInt();
        int a[]=new int[n];
        int b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=in.readInt();
            b[i]=a[i];
        }
        Arrays.sort(b);
        if(b[n-1]-b[0]>k)
        {
            out.printLine("NO");
            return;
        }
        out.printLine("YES");
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<a[i];j++)
            {
                out.print((j%k+1)+" ");
            }
            out.printLine();
        }
    }
}

class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }
    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}

import sys,math,bisect
from random import randint
inf = float('inf')
mod = 998244353
"========================================"
def lcm(a,b):
    return int((a/math.gcd(a,b))*b)
def gcd(a,b):
    return int(math.gcd(a,b))
def tobinary(n):
    return bin(n)[2:]
def binarySearch(a,x):
    i = bisect.bisect_left(a,x)
    if i!=len(a) and a[i]==x:
        return i
    else:
        return -1
def lowerBound(a, x):
    i = bisect.bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
def upperBound(a,x):
    i = bisect.bisect_right(a,x)
    if i!= len(a)+1 and a[i-1]==x:
        return (i-1)
    else:
        return -1
def primesInRange(n):
    ans = []
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n+1):
        if prime[p]:
            ans.append(p)
    return ans
def primeFactors(n):
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n = n // 2
    for i in range(3,int(math.sqrt(n))+1,2):
        while n % i== 0:
            factors.append(i)
            n = n // i
    if n > 2:
        factors.append(n)
    return factors
def isPrime(n,k=5):
    if (n <2):
        return True
    for i in range(0,k):
        a = randint(1,n-1)
        if(pow(a,n-1,n)!=1):
            return False
    return True
"========================================="
"""
n = int(input())
n,k = map(int,input().split())
arr = list(map(int,input().split()))
"""
from collections import deque,defaultdict,Counter
import heapq,string

n,k = map(int,input().split())
arr = list(map(int,input().split()))
if max(arr)-min(arr)>k:
    print('NO')
else:
    ans = [[0]*i for i in arr]
    c=min(arr)
    k=1
    for i in range(n):
        for j in range(min(arr)):
            ans[i][j]=1
    while c<max(arr):
        for i in range(n):
            if len(ans[i]) > c:
                ans[i][c]=k
        c+=1
        k+=1
    print('YES')
    for i in ans:
        print(*i)


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
mx = -10 ** 10
mix = 10 ** 10
my = mx
miy = mix
for _ in range(int(input())):
    a, b = map(int, input().split())
    mx = max(mx, a)
    mix = min(mix, a)
    my = max(my, b)
    miy = min(miy, b)
ans = max(mx - mix, my - miy)
print(ans * ans)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        long largestx = Long.MIN_VALUE;
        long largesty = Long.MIN_VALUE;
        long smallestx = Long.MAX_VALUE;
        long smallesty = Long.MAX_VALUE;
        int n = Integer.parseInt(new StringTokenizer(br.readLine()).nextToken());
        for(int i = 0; i < n; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            long x = Long.parseLong(st.nextToken());
            if(x > largestx)
                largestx = x;
            if(x < smallestx)
                smallestx = x;
            long y = Long.parseLong(st.nextToken());
            if(y > largesty)
                largesty = y;
            if(y < smallesty)
                smallesty = y;
        }
        long a = Math.max(largestx - smallestx, largesty - smallesty);
        System.out.print(a * a);
    }
}


n=int(input())
a,b=input(),""
x,y=1,0
for i in range(n-1):
    s=input()
    if a==s:
        x+=1
    else:
        b=s
        y+=1
print([b,a][x>y])

19
XBCP
TGACNIH
XBCP
XBCP
XBCP
XBCP
XBCP
TGACNIH
XBCP
XBCP
XBCP
XBCP
XBCP
TGACNIH
XBCP
XBCP
TGACNIH
TGACNIH
XBCP

100
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
M
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA
HA

100
G
G
S
S
G
G
S
S
G
S
S
S
G
S
G
G
S
G
S
S
G
S
S
S
S
S
G
S
G
S
S
G
G
G
S
S
S
S
G
S
S
G
G
G
G
G
S
G
G
S
S
S
S
S
G
G
S
G
G
G
G
G
S
S
G
S
S
S
S
G
S
S
G
S
G
G
G
G
G
G
G
G
G
G
G
S
S
G
S
S
S
S
G
G
G
S
G
G
G
S

89
H
VOCI
VOCI
H
VOCI
H
H
VOCI
VOCI
VOCI
H
H
H
VOCI
VOCI
VOCI
H
VOCI
VOCI
H
VOCI
VOCI
VOCI
H
VOCI
H
VOCI
H
VOCI
H
VOCI
VOCI
H
VOCI
VOCI
VOCI
VOCI
VOCI
VOCI
H
VOCI
VOCI
VOCI
VOCI
H
VOCI
H
H
VOCI
H
VOCI
H
VOCI
VOCI
VOCI
VOCI
VOCI
VOCI
VOCI
H
H
VOCI
H
H
VOCI
H
VOCI
H
VOCI
VOCI
H
VOCI
VOCI
VOCI
VOCI
VOCI
VOCI
VOCI
H
H
H
H
H
VOCI
H
VOCI
H
VOCI
VOCI

ABC HA B B ABCXYZABCXYZ C C B ABCXYZABC B XYZ XYZ B E QCCYXL ABA ABCXYZABCXYZ B B XBCP XYZ BABA A B ABC ABA BABA E A G ABCXYZABCXYZ C A E ABA VOCI ABC E A ABCXYZ XYZ ABC B B ABA C XYZ XYZ BABA W

#include <bits/stdc++.h>
using namespace std;
int main() {
  int t, s;
  while (cin >> t) {
    string a[1005];
    for (int i = 0; i < t; i++) {
      cin >> a[i];
    }
    sort(a, a + t);
    cout << a[t / 2] << endl;
  }
}


#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int n;
struct node {
  int v, w;
  node() {}
  node(int _v, int _w) : v(_v), w(_w) {}
};
vector<node> ve[110];
int ans;
bool flag;
void dfs(int fa, int u) {
  if (u == 1 && fa != -1) flag = true;
  if (flag) return;
  for (int i = 0; i < ve[u].size(); i++) {
    if (flag) return;
    int v = ve[u][i].v;
    int w = ve[u][i].w;
    if (v == fa) continue;
    if (w < 0) ans += (-w);
    dfs(u, v);
  }
}
int main() {
  while (scanf("%d", &n) != EOF) {
    for (int i = 0; i < 110; i++) ve[i].clear();
    int sum = 0;
    for (int i = 0; i < n; i++) {
      int t1, t2, t3;
      scanf("%d%d%d", &t1, &t2, &t3);
      sum += t3;
      ve[t1].push_back(node(t2, t3));
      ve[t2].push_back(node(t1, -t3));
    }
    ans = 0;
    flag = false;
    dfs(-1, 1);
    printf("%d\n", min(ans, sum - ans));
  }
  return 0;
}

import java.util.*;
import java.lang.*;
import java.math.*;

public class A {

    Scanner sc = new Scanner(System.in);
    int n;
    int[][] road;
    int c = 0;

    void run(){

        int nowP = 0;
        int nextP ;
        int[] point =new int [2];
        int[][] vRoad;

        n = sc.nextInt();

        road = new int [n][3];
        vRoad = new int [n][3];

        for (int i=0;i<n;i++) {
            road[i][0] = sc.nextInt();
            road[i][1] = sc.nextInt();
            road[i][2] = sc.nextInt();
            vRoad[i][0] = road[i][0];
            vRoad[i][1] = road[i][1];
            vRoad[i][2] = road[i][2];
        }

        int cost1 = 0;
        do {
            point = retNum(nowP);
            nextP = point[0];

            if ( point[1] == 1 ) {
                revRoad( nextP );
                cost1 += road[nextP][2];
//              System.out.println(cost1);
            }
            nowP = nextP;

//          System.out.println(road[nowP][0] + " " + road[nowP][1]);

        }while ( nextP != 0 );

        road = vRoad;

//      System.out.println();

        int cost2 = 0;

        nowP = 0;

        revRoad( nowP );

        cost2 += road[nowP][2];
//      System.out.println(cost2);

        do {
            point = retNum(nowP);
            nextP = point[0];

            if (point[1] == 1) {
                revRoad( nextP );
                cost2 += road[nextP][2];
//              System.out.println(cost1);
//              System.out.println("a");
            }

//          System.out.println(road[nowP][0] + " " + road[nowP][1]);

            nowP = nextP;

        }while ( nextP != 0 );

//      System.out.println(cost2);

        int c = Math.min(cost1, cost2);

        System.out.println(c);

    }

    int[] retNum(int num) {

        int[] re = new int[2];

        for (int i=0;i<n;i++) {
            for (int j=0;j<2;j++) {
                if ( i != num ) {
                    if ( road[num][1] == road[i][j] ) {

                        re[0] = i;
                        re[1] = j;
                        return re;
                    }
                }
            }
        }

        return re;

    }

    void revRoad(int num) {

        int tmp = road[num][0];
        road[num][0] = road[num][1];
        road[num][1] = tmp;

    }

    public static void main(String[] args){

        new A().run();

    }

}


import re
from collections import Counter

class Task:
    data = []
    delta = 0
    friends = set()

    def getData(self):
        n, self.delta = [int(x) for x in input().split(" ")]
        for i in range(0, n):
            self.data += [input()]

    def solve(self):
        messages = dict()
        for line1 in self.data:
            A1, B1, time1 = line1.split(" ")
            for line2 in self.data:
                A2, B2, time2 = line2.split(" ")
                if A2 == B1 and B2 == A1 and \
                        0 < abs(int(time2) - int(time1)) <= self.delta:
                    self.friends.add(min(A2 + " " + B2, B2 + " " + A2))

    def printAnswer(self):
        print(len(self.friends))
        for pair in self.friends:
            print(pair)

task = Task();
task.getData();
task.solve();
task.printAnswer();

10 2
fxn ipntr 0
ipntr fxn 1
fxn ipntr 1
pfvpfteadph ipntr 2
fxn pfvpfteadph 4
ipntr fxn 4
pfvpfteadph fxn 5
fxn pfvpfteadph 5
pfvpfteadph ipntr 6
ipntr pfvpfteadph 6

8 1000 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g f 6

10 1 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h i 7 i h 8

9 10 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h g 7

7 100 a b 0 b c 1 c d 2 d e 3 e f 4 f e 5

8 100 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g f 6

4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4

9 100 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h g 7

7 1000 a b 0 b c 1 c d 2 d e 3 e f 4 f e 5

10 10 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h i 7 i h 8

10 2
rvmykneiddpqyf jdhmt 0
wcsjvh jdhmt 0
jdhmt rvmykneiddpqyf 1
rvmykneiddpqyf jdhmt 1
wcsjvh rvmykneiddpqyf 2
rvmykneiddpqyf jdhmt 2
jdhmt rvmykneiddpqyf 3
jdhmt wcsjvh 5
jdhmt wcsjvh 5
rvmykneiddpqyf jdhmt 6

9 1000 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h g 7

10 2
liazxawm spxwktiqjgs 0
nolq liazxawm 1
liazxawm nolq 2
liazxawm spxwktiqjgs 2
nolq liazxawm 3
spxwktiqjgs liazxawm 3
spxwktiqjgs liazxawm 3
spxwktiqjgs liazxawm 3
spxwktiqjgs nolq 3
nolq spxwktiqjgs 4

8 10 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g f 6

9 1 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h g 7

10 2
yltec xnzdtcgzxqqltvpfr 0
fxxhcmbzzg xnzdtcgzxqqltvpfr 0
fxxhcmbzzg xnzdtcgzxqqltvpfr 0
fxxhcmbzzg yltec 1
fxxhcmbzzg xnzdtcgzxqqltvpfr 2
fxxhcmbzzg yltec 2
yltec fxxhcmbzzg 3
yltec xnzdtcgzxqqltvpfr 3
yltec xnzdtcgzxqqltvpfr 5
fxxhcmbzzg yltec 6

10 100 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g h 6 h i 7 i h 8

8 1 a b 0 b c 1 c d 2 d e 3 e f 4 f g 5 g f 6

7 10 a b 0 b c 1 c d 2 d e 3 e f 4 f e 5

3
liazxawm nolq
spxwktiqjgs liazxawm
nolq spxwktiqjgs


import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	PrintWriter out = new PrintWriter(System.out);
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok = new StringTokenizer("");
    String next() throws IOException {
        if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
        return tok.nextToken();
    }
    int ni() throws IOException { return Integer.parseInt(next()); }
    long nl() throws IOException { return Long.parseLong(next()); }

    void solve() throws IOException {
        int n=ni();
        //Integer[][]A=new Integer[n-1][2];
        int[]B=new int[n-1];
        boolean f=true;

        for (int x=0;x<n-1;x++) {
            int a=ni();
            if (f) {
                if (a==-1) { f=false; x--; }
                else B[x]=0;
            }
            else B[x]=a;
        }

        if (f) { System.out.println(0); return; }

        boolean[]F=new boolean[n-1];

        int r=n;

        int q=n-2;
        long ans = 0;
        int nextmin=B[q];
        int nmi=q;
        int p=0;
        F[q]=true;

        while (r>2) {
            ans+=nextmin;
            nextmin=Integer.MAX_VALUE;
            q=n-2;
            nmi=q;
            p=p+r/2;
            for (int y=0;y<=p;y++) {
                if (!F[q]) {
                    if (B[q]<nextmin) { nextmin=B[q]; nmi=q; }
                }
                q--;
            }
            F[nmi]=true;
            r=r>>1;
        }
        ans+=nextmin;
        System.out.println(ans);
    }

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

#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int n;
  cin >> n;
  long long int log = log2(n), rem;
  rem = log;
  vector<long long int> arr(n);
  for (long long int i = 0; i < n; i++) cin >> arr[i];
  reverse((arr).begin(), (arr).end());
  while (arr.back() != -1) arr.pop_back();
  arr.pop_back();
  reverse((arr).begin(), (arr).end());
  long long int win = n - arr.size();
  while (win > 1) {
    rem--;
    win /= 2;
  }
  if (arr.size() == 0) {
    cout << 0;
    return 0;
  }
  long long int ans = 0;
  long long int lose = n / 2;
  priority_queue<long long int, vector<long long int>, greater<long long int>>
      Q;
  Q.push(arr.back());
  arr.pop_back();
  while (rem > 0) {
    ans += Q.top();
    Q.pop();
    for (long long int i = 0; i < lose && !arr.empty(); i++) {
      Q.push(arr.back());
      arr.pop_back();
    }
    lose /= 2;
    rem--;
  }
  cout << ans;
}


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main implements Runnable {

    private int n;
    private int nn;
    private boolean[][] gr;
    private long[][] D;

    // ////////////////////////////////////////////////////////////////////
    // Solution

    private void solve() throws Throwable {
        n = nextInt();
        nn = 1 << n;
        gr = new boolean[n][n];
        int m = nextInt();
        for (int i = 0; i < m; i++) {
            int a = nextInt() - 1, b = nextInt() - 1;
            gr[a][b] = gr[b][a] = true;
        }
        D = new long[n][nn];
        for (int i = 0; i < n; i++) {
            Arrays.fill(D[i], -1);
        }
        long count = 0;
        for (int i = 0; i < n; i++) {
            count += getD(i, i, 1, 1 << i);
        }
        pw.println(count / 2);
    }

    private long getD(int first, int last, int cnt, int mask) {
        if (D[last][mask] != -1) return D[last][mask];
        long ans = 0;
        if (cnt >= 3 && gr[first][last])
            ans++;
        for (int i = first + 1; i < n; i++) {
            if (gr[last][i] && (mask & (1 << i)) == 0) {
                ans += getD(first, i, cnt + 1, mask | (1 << i));
            }
        }
        D[last][mask] = ans;
        return ans;
    }

    // ////////////////////////////////////////////////////////////////////
    // Utility functions

    PrintWriter pw;
    BufferedReader in;
    StringTokenizer st;

    void initStreams() throws FileNotFoundException {
        //System.setIn(new FileInputStream("2"));
        in = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
    }

    String nextString() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    int nextInt() throws NumberFormatException, IOException {
        return Integer.parseInt(nextString());
    }

    long nextLong() throws NumberFormatException, IOException {
        return Long.parseLong(nextString());
    }

    double nextDouble() throws NumberFormatException, IOException {
        return Double.parseDouble(nextString());
    }

    static Throwable sError;

    public static void main(String[] args) throws Throwable {
        Thread t = new Thread(new Main());
        t.start();
        t.join();
        if (sError != null) {
            throw sError;
        }
    }

    public void run() {
        try {
            initStreams();
            solve();
        } catch (Throwable e) {
            sError = e;
        } finally {
            if (pw != null)
                pw.close();
        }
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class E {

	static final long MIN = -200000000010L;
	static final long MAX = 200000000010L;
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), false);
		String[] parts = br.readLine().split(" ");
		long h = Long.parseLong(parts[0]);
		int n = Integer.parseInt(parts[1]);
		long[] lives = new long[n];
		long minLive = MAX;
		long sumLive = 0;
		parts = br.readLine().split(" ");
		for (int i = 0; i < n; ++i) {
			lives[i] = Long.parseLong(parts[i]);
			sumLive += lives[i];
			minLive = Math.min(minLive, sumLive);
		}
		if (sumLive >= 0 && h + minLive > 0) {
			out.println(-1);
		} else {
			long fullRounds = sumLive >= 0 || h + minLive <= 0 ? 0 : (h + minLive) / -sumLive;
			h += fullRounds * sumLive;
			long ans = fullRounds * n;
			while (h > 0) {
				for (int i = 0; i < n; ++i) {
					++ans;
					h += lives[i];
					if (h <= 0) {
						break;
					}
				}
			}
			out.println(ans);
		}
		out.close();
	}

}

INF = 10 ** 13

h, n = map(int, input().split())
a = list(map(int, input().split()))
b = a[:]
for i in range(1, n):
    b[i] += b[i - 1]
low = min(b)
tot = b[-1]

if h + low <= 0:
    lo = 0
else:
    lo, hi = 0, INF
    while lo < hi:
        mid = (lo + hi) // 2
        cur = h + mid * tot + low
        if cur <= 0:
            hi = mid
        else:
            lo = mid + 1
if lo == INF:
    print(-1)
else:
    steps = lo * n
    cur = h + lo * tot
    for i in range(n):
        cur += a[i]
        steps += 1
        if cur <= 0:
            break
    print(steps)


//package javaapplication3;

import java.util.Scanner;
import java.util.Arrays;

/**
 *
 * @author Mahmoud
 */
public class StringCodeforces {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        byte x=sc.nextByte();

        for(int i=0;i<x;i++)
        {
            char []a=sc.next().toCharArray();

            Arrays.sort(a);

           if(a[0] != a[a.length-1]){
               for(char w :a)System.out.print(w);
                System.out.println();
           }

           else
           {
                System.out.println(-1);
           }

        }

}

}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  int flag = 1;
  string str;
  cin >> n;
  while (n--) {
    cin >> str;
    int len = str.length();
    for (int i = 0; i < len / 2; i++) {
      if (str[i] != str[len - 1 - i]) {
        flag = 0;
      }
    }
    if (flag) {
      sort(str.begin(), str.end());
      if (str[0] == str[len - 1]) {
        cout << -1 << endl;
        continue;
      }
    }
    cout << str << endl;
    flag = 1;
  }
  return 0;
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Arrays.fill;

/**
 * Created by timur on 28.03.15.
 */

public class TaskD {
    boolean eof;
    BufferedReader br;
    StringTokenizer st;
    PrintWriter out;

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

    public String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return "-1";
            }
        }
        return st.nextToken();
    }

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

    public long nextLong() {
        return Long.parseLong(nextToken());
    }

    double nextDouble() {
        return Double.parseDouble(nextToken());
    }

    String nextLine() throws IOException {
        return br.readLine();
    }

    void run() throws IOException {
        InputStream input = System.in;
        PrintStream output = System.out;
        try {
            File f = new File("a.in");
            if (f.exists() && f.canRead()) {
                input = new FileInputStream(f);
                output = new PrintStream("a.out");
            }
        } catch (Throwable e) {
        }
        br = new BufferedReader(new InputStreamReader(input));
        out = new PrintWriter(output);
        solve();
        br.close();
        out.close();
    }

    void solve() {
        long n = nextLong(), m = nextLong();
        long x;
        if (n > m) {
            x = m;
            m = n;
            n = x;
        }
        if (n > 3) {
            out.print(n * m - (n * m) % 2);
        } else {
            long s = m - m % 6;
            long h = 0, o = m % 6;
            if (n == 1) {
                if (o == 4) {
                    h = 2;
                } else if (o == 5) {
                    h = 4;
                } else {
                    h = 0;
                }
            } else if (n == 2) {
                if (o == 3) {
                    h = 4;
                } else if (o == 4) {
                    h = 8;
                } else if (o == 5) {
                    h = 10;
                } else {
                    h = 0;
                }
            } else if (n == 3) {
                if (o == 2) {
                    h = 4;
                } else if (o == 3) {
                    h = 8;
                } else if (o == 4) {
                    h = 12;
                } else if (o == 5) {
                    h = 14;
                } else {
                    h = 0;
                }
            }
            if (n + m > 9 && n > 1) {
                out.print(n * m - (n * m) % 2);
                return;
            }
            out.print(s * n + h);
        }

    }

}

n, m = map(int, input().split())

if n > m:
    n, m = m, n

if n == 1:
    ans = (m//6)*6+2*max(m%6-3, 0)
    print(ans)

elif n == 2:
    if m == 2:
        print(0)
    elif m == 3:
        print(4)
    elif m == 7:
        print(12)
    else:
        print(n*m)

else:
    ans = ((n*m)//2)*2
    print(ans)


#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 9;
const int MAXN = 1e5 + 5;
long long n, a, b, k, res, ans;
char s[MAXN];
long long qpow(long long a, long long p) {
  long long res = 1;
  while (p) {
    if (p & 1) res = res * a % MOD;
    a = a * a % MOD;
    p >>= 1;
  }
  return res;
}
int main() {
  cin >> n >> a >> b >> k;
  scanf("%s", s + 1);
  long long v = qpow(a, MOD - 2), x = qpow(a, n), len = (n + 1) / k;
  for (int i = 1; i <= k; i++) {
    if (s[i] == '+')
      res = (res + x) % MOD;
    else
      res = (res - x) % MOD;
    x = x * v % MOD * b % MOD;
  }
  x = qpow(v, k) * qpow(b, k) % MOD;
  if (x == 1)
    ans = res * len % MOD;
  else
    ans = res * (qpow(x, len) - 1) % MOD * qpow(x - 1, MOD - 2) % MOD;
  if (ans < 0) ans += MOD;
  cout << ans << endl;
  return 0;
}

import java.util.*;
import java.io.*;
/*
	1
7
8 6 12 10 12 8 10

4
4
1 2 1 1
2 2 2 1
10 6 11 10
 */
public class Crypto {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PrintWriter out = new PrintWriter(System.out);
		Scanner sc = new Scanner(System.in);
		final int MOD = 1000000009;
		long n = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt(), k = sc.nextInt();
		sc.nextLine();
		char ch[] = sc.nextLine().toCharArray();
		long A = 0, N = (n+1)/k, r = powerMod((b * powerMod(a, MOD-2, MOD))%MOD, k, MOD);
		for(int i = 0; i<k; i++) {
			long temp = 1;
			if(ch[i] == '-') temp = -1;
			A = ( A + (temp * powerMod(a,n-i,MOD) * powerMod(b, i, MOD))%MOD + MOD)%MOD;
			//System.out.println(A);
			//A = (A+MOD)%MOD;
		}
		long fa = 0;
		if(r==1) {
			fa = (N*A)%MOD;
		}
		else {
			long a1 = (powerMod(r, N, MOD) -1 + MOD)%MOD;
			long a2 = powerMod((r-1+MOD)%MOD, MOD-2, MOD);
			fa = (A * ((a1 * a2)%MOD))%MOD;
		}
		//System.out.println(A+" "+r+" "+N);
		System.out.println((fa+MOD)%MOD);
		out.close();
	}
	static long powerMod(long a, long b, int MOD) {
		long ans = 1;
		while(b>0) {
			if(b%2==0) {
				a *= a;
				a%=MOD;
				b/=2;
			}
			else {
				b-=1;
				ans *= a;
				ans%=MOD;
			}
		}
		return ans;
	}
	public static int[] radixSort(int[] f){ return radixSort(f, f.length); }
	public static int[] radixSort(int[] f, int n)
	{
		int[] to = new int[n];
		{
			int[] b = new int[65537];
			for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
			for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
			for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
			int[] d = f; f = to;to = d;
		}
		{
			int[] b = new int[65537];
			for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
			for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
			for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
			int[] d = f; f = to;to = d;
		}
		return f;
	}
	static int max(int a, int b) { return (a>b)?a:b;}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;

public class ER {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Queue<Character> q = new LinkedList<>();
        String v = "aeiouy";
        char[] s = sc.next().toCharArray();
        for (int i = 0; i < s.length; ++i)
            q.add(s[i]);

        StringBuilder sb = new StringBuilder();
        char cur = q.remove();
        sb.append(cur);
        while (!q.isEmpty()) {
            char top = q.remove();
            if (v.indexOf(top) != -1 && v.indexOf(cur) != -1)
                continue;
            else if (v.indexOf(top) == -1 || v.indexOf(cur) == -1) {
                cur = top;
                sb.append(cur);
            }
        }
        System.out.println(sb);
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

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

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            String x = next();
            StringBuilder sb = new StringBuilder("0");
            double res = 0, f = 1;
            boolean dec = false, neg = false;
            int start = 0;
            if (x.charAt(0) == '-') {
                neg = true;
                start++;
            }
            for (int i = start; i < x.length(); i++)
                if (x.charAt(i) == '.') {
                    res = Long.parseLong(sb.toString());
                    sb = new StringBuilder("0");
                    dec = true;
                } else {
                    sb.append(x.charAt(i));
                    if (dec)
                        f *= 10;
                }
            res += Long.parseLong(sb.toString()) / f;
            return res * (neg ? -1 : 1);
        }

        public boolean ready() throws IOException {
            return br.ready();
        }

    }
}

9banaaaaaa
```

Note that the length of each sample input is less than or equal to 40 tokens, and each sample input conforms to the input data format specified in the problem description.

tomato werd bana bana bana banana bana banana bana elephant bana betiful bana apo bana bana potato a banana bana a carrot word cabbage bana bana hello a bana bana word banana xxxahg computer apple orange a werd banana bana bana bana bana o

#include <bits/stdc++.h>
using namespace std;
char c[10] = {'a', 'e', 'i', 'o', 'u', 'y'};
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  string s;
  cin >> s;
  string ans;
  bool t = 0;
  for (int i = 0; i < s.size(); i++) {
    bool is = 0;
    for (int j = 0; j < 6; j++) {
      if (s[i] == c[j]) is = 1;
    }
    if (is == 1 && t == 0) {
      t = 1;
      ans += s[i];
    } else if (is == 0 && t == 1) {
      t = 0;
      ans += s[i];
    } else if (is == 0 && t == 0) {
      ans += s[i];
    }
  }
  cout << ans << '\n';
  return 0;
}


n, m = map(int, input().split())

pc = [(0, 0) for _ in range(n)]

party_votes = [0 for _ in range(m)]

for i in range(n):
    p, c = map(int, input().split())
    pc[i] = (p - 1, c)
    party_votes[p - 1] += 1

pc.sort(key=lambda x: x[1])

min_cost = 10**20

for votes in range(n + 1):
    _party_votes = party_votes[:]
    dangerous = list(map(lambda party: _party_votes[party] >= votes, range(0, m)))
    used = list(map(lambda i: pc[i][0] == 0, range(n)))
    cur_cost = 0
    for i in range(n):
        if dangerous[pc[i][0]] and pc[i][0] != 0:
            cur_cost += pc[i][1]
            _party_votes[0] += 1
            _party_votes[pc[i][0]] -= 1
            dangerous[pc[i][0]] = _party_votes[pc[i][0]] >= votes
            used[i] = True
    for i in range(n):
        if _party_votes[0] >= votes:
            break
        if not used[i]:
            _party_votes[0] += 1
            cur_cost += pc[i][1]
    min_cost = min(min_cost, cur_cost)

print(min_cost)

import java.io.*;
import java.util.*;

public class GFG {

    static int v,p;
    static int vcnt[]=new int[3001];
    static class Wrapper implements Comparable<Wrapper>
    {
       int pre;
       int c;
       Wrapper(int pre,int c)
       {
           this.pre=pre;
           this.c=c;
       }
       public int compareTo(Wrapper w)
       {
           return this.c-w.c;
       }
    }
    static ArrayList<Wrapper> list=new ArrayList<>();
    static long solveUtil()
    {
        long cost=Long.MAX_VALUE;
        Collections.sort(list);
        boolean flag[]=new boolean[v+1];

        for(int m=1;m<=(v-vcnt[1]);m++){

            long lcost=0;
            int cnt=0;
            Arrays.fill(flag,true);
            Arrays.fill(vcnt,0);
            for(int i=1;i<=v;i++)
               vcnt[list.get(i-1).pre]++;

            for(int i=1;i<=v;i++)
            {
                if(list.get(i-1).pre!=1&&vcnt[list.get(i-1).pre]>=m)
                  {
                      flag[i]=false;
                      vcnt[list.get(i-1).pre]--;
                      cnt++;
                      lcost+=list.get(i-1).c;
                  }
            }

                for(int i=1;i<=v&&cnt<m-vcnt[1];i++)
                {
                    if(list.get(i-1).pre!=1&&flag[i])
                    {
                       flag[i]=false;
                       vcnt[list.get(i-1).pre]--;
                       cnt++;
                       lcost+=list.get(i-1).c;
                    }
                }

           // System.out.println(lcost+" "+cnt);

            if(cnt>=(m-vcnt[1]))
             cost=Math.min(lcost,cost);
        }
        return cost;
    }

    static long solve()
    {
        if(v==1)
        {
            if(list.get(0).pre==1)
              return 0;
            else
              return (list.get(0).c);
        }
        for(int i=1;i<=v;i++)
           vcnt[list.get(i-1).pre]++;

        boolean flag=false;
        for(int i=2;i<=p;i++)
        {
            if(vcnt[i]>=vcnt[1])
            {
              flag=true;
              break;
            }
        }
        if(!flag)
          return 0;

        return solveUtil();
    }
	public static void main (String[] args) throws Exception{

		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		String s[]=bf.readLine().trim().split("\\s+");
		v=Integer.parseInt(s[0]);
		p=Integer.parseInt(s[1]);
		for(int i=0;i<v;i++)
		{
		    s=bf.readLine().trim().split("\\s+");
		    int pre=Integer.parseInt(s[0]);
		    int c=Integer.parseInt(s[1]);
		    list.add(new Wrapper(pre,c));
		}
		System.out.println(solve());
	}
}


#include <bits/stdc++.h>
long long mod = 1e9 + 7;
const int MAX = 1e5 + 5;
using namespace std;
long long get_binary(int n) {
  long long binary = 0;
  int remainder, i = 1, step = 1;
  while (n != 0) {
    remainder = n % 2;
    n /= 2;
    binary += remainder * i;
    i *= 10;
  }
  return binary;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  long long cnt = 0;
  for (int i = 1; i <= (int)pow(2, 10) - 1; i++) {
    int num = i;
    long long bin = get_binary(num);
    if (bin <= n) cnt++;
  }
  cout << cnt;
  return 0;
}

n=int(input())

a=[]
c=int
for i in range(515):
    a.append(c(bin(i)[2:]))
a.remove(0)
ans=0
for i in a:
    if i<=n:
        ans+=1

print(ans)


#include <bits/stdc++.h>
using namespace std;
int n, k;
int arr[100000];
int taken[256] = {-1};
int picked, cur;
signed main() {
  cin >> n >> k;
  for (int i = 0; i < 256; i++) taken[i] = -1;
  for (int i = 0; i < n; i++) {
    cin >> cur;
    picked = cur;
    for (int j = cur; j >= max(0, cur - k + 1); j--) {
      if (taken[j] == -1) {
        picked = j;
      }
      if (taken[j] != -1) {
        if (cur - taken[j] + 1 <= k) picked = taken[j];
        break;
      }
    }
    for (int j = picked; j <= cur; j++) {
      taken[j] = picked;
    }
    cout << picked << ' ';
  }
  return 0;
}

R = lambda: map(int, input().split())

n, k = R()
a = list(range(0, 257)); v = [1]*257
for p in R():
    if v[p]:
        t = p
        while t >= 0 and p-a[t]<=k-1: t -= 1
        t += 1
        for i in range(t, p+1): a[i] = a[t]; v[i] = 0
    print(a[p], end=' ')


import java.util.*;
public class modcrab
{
////heal=1
//strike=0
public static int decide(int a1,int a2,int c1,int h1,int h2)
{
if(h2-a1<=0)
return 0; //strike
if(h1-a2<=0)
return 1; //heal
return 0;//strike
}
public static void main(String[] args)
{
ArrayList<Integer> al=new<Integer> ArrayList();
Scanner in=new Scanner(System.in);
int a1;
int a2;
int c1;
int h1;
int h2;
int n=0; //num of phases required
h1=in.nextInt();
a1=in.nextInt();
c1=in.nextInt();
h2=in.nextInt();
a2=in.nextInt();
while(h1>0 && h2>0)
{
if(decide(a1,a2,c1,h1,h2)==0)
{//strike
al.add(0);
h2=h2-a1;
h1=h1-a2;
}
else
{//heal
al.add(1);
h1=h1+c1;
h1=h1-a2;
}
n++;
}
System.out.println(n);
for(int i=0;i<al.size();i++)
{if(al.get(i)==0)
System.out.println("STRIKE");
else
System.out.println("HEAL");
}
}
}

21
STRIKE
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
STRIKE
STRIKE

11
STRIKE
HEAL
STRIKE
HEAL
STRIKE
STRIKE
HEAL
STRIKE
HEAL
STRIKE
STRIKE

9
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
HEAL
STRIKE
STRIKE

class Character:
    def __init__(self, hPoints, attPoints, healPoints):
        self.hPoints = hPoints
        self.attPoints = attPoints
        self.healPoints = healPoints
    def attack(self, boss):
        boss.setHP(boss.getHP() - self.attPoints)
    def recAttack(self, boss):
        self.hPoints -= boss.getAP()
    def heal(self):
        self.hPoints += self.healPoints
    def getHP(self):
        return self.hPoints
    def getAP(self):
        return self.attPoints
    def getHLP(self):
        return self.healPoints
class Boss:
    def __init__(self, hPoints, attPoints):
        self.hPoints = hPoints
        self.attPoints = attPoints
    def setHP(self, nextHP):
        self.hPoints = nextHP
    def getAP(self):
        return self.attPoints
    def getHP(self):
        return self.hPoints

def game(vova, modcrab):
    numTurns = 0
    vovaHP = vova.getHP()
    vovaAP = vova.getAP()
    vovaHeal = vova.getHLP()
    mcHP = modcrab.getHP()
    mcAP = modcrab.getAP()
    while mcHP > 0:
        if vovaHP - mcAP > 0 or vovaAP >= mcHP:
            mcHP -= vovaAP
            vovaHP -= mcAP
        else:
            vovaHP += vovaHeal
            vovaHP -= mcAP
        numTurns += 1
    print(numTurns)
    while modcrab.getHP() > 0:
        if vova.getHP() - modcrab.getAP() > 0 or vova.getAP() >= modcrab.getHP():
            vova.attack(modcrab)
            vova.recAttack(modcrab)
            print('STRIKE')
        else:
            vova.heal()
            vova.recAttack(modcrab)
            print('HEAL')
    return

vStats = input().split()
mStats = input().split()

vova = Character(int(vStats[0]),int(vStats[1]), int(vStats[2]))
modcrab = Boss(int(mStats[0]),int(mStats[1]))

game(vova, modcrab)


#include <bits/stdc++.h>
int p(int n) {
  int i, k = 1;
  for (i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      k = 0;
      break;
    }
  }
  if (n == 3 || n == 2)
    return 1;
  else
    return k;
}
int main() {
  int n, m, i;
  while (scanf("%d%d", &n, &m) != EOF) {
    for (i = n + 1; i <= m; i++) {
      if (p(i)) break;
    }
    if (i == m)
      printf("YES\n");
    else
      printf("NO\n");
  }
  return 0;
}

YES YES NO NO NO NO NO YES NO NO NO NO NO YES NO YES NO NO NO NO NO NO NO YES YES NO NO NO NO YES YES NO YES NO YES YES NO YES NO NO YES YES NO NO NO YES NO YES NO YES YES NO YES YES YES YES NO YES NO NO YES NO NO NO NO NO NO

from math import ceil, sqrt

def array(arr, struc):
    return (list(map(struc, arr.split())))

def isPrime(x):
    for i in range(2, ceil(sqrt(x))+1):
        if x % i == 0:
            return False

    return True

arr = array(input(), int)

prime1 = arr[0]
prime2 = arr[1]
counter = 0
tmp = prime1 + 1

while tmp <= prime2:
    if isPrime(tmp):
        if tmp == prime2:
            counter = 1
            print('YES')
            break
        else:
            break

    tmp += 1

if counter == 0:
    print('NO')


input()
A = list(map(int, input().split(' ')))
root=-1
for i,a in enumerate(A) :
    if i == a-1 :
        root = i
        break
v = [False]*len(A)
if root>-1 :
    v[root]=True
ans= 0
for i,a in enumerate(A) :
    if v[i] :
        continue
    v[i]= True
    l=[i]
    a-=1
    while not v[a] :
        l.append(a)
        v[a]=True
        a=A[a]-1
    if a in l: #new cycle
        if root==-1:
            A[a]=a+1
            root=a
            ans+=1
        else :
            A[a]=root+1
            ans+=1
print(ans)
print(' '.join(map(str,A)))

#include <bits/stdc++.h>
using namespace std;
const int maxn = 222222;
int a[maxn];
int f[maxn];
int book[maxn];
int find(int x) {
  if (f[x] == x) return x;
  return f[x] = find(f[x]);
}
int merge(int x, int y) {
  int u = find(x);
  int v = find(y);
  if (u != v) {
    f[v] = u;
    return 1;
  }
  return 0;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    f[i] = i;
  }
  int cnt = 0;
  int pre = -1;
  for (int i = 1; i <= n; i++) {
    if (!merge(a[i], i) && a[i] != i) {
      cnt++;
      if (pre != -1) {
        merge(i, pre);
      }
      pre = i;
      book[i] = 1;
    }
  }
  for (int i = 1; i <= n; i++) {
    if (i == f[i]) {
      cnt++;
      book[i] = 1;
      if (pre != -1) {
        merge(i, pre);
      }
      pre = i;
    }
  }
  printf("%d\n", cnt - 1);
  for (int i = 1; i <= n; i++) {
    if (book[i])
      printf("%d ", f[i]);
    else
      printf("%d ", a[i]);
  }
  return 0;
}


import java.math.BigInteger;
import java.util.*;

import static java.lang.Math.abs;
import static java.lang.Math.exp;
import static java.lang.Math.floor;

public class Main {
    static Scanner scanner = new Scanner(System.in);
    static long  sum[]=new long[100000];

    public static void main(String[] args) {
        int n = scanner.nextInt(),o1=0,o0=0;
        scanner.nextLine();
        String temp=scanner.nextLine();
        for (int i=0;i<n;i++){
            if (temp.charAt(i)=='0'){
                o0++;
            }else {
                o1++;
            }
        }
        System.out.println(Math.abs(o0-o1));
    }

}

n = int(input())
s = input()
x = s.count('0')
y = s.count('1')
print(abs(x-y))


palindrom = lambda s: s == s[::-1]
printans = lambda l: print(''.join(l))
s = list(input())

for i in range(len(s)+1):
    for letter in 'abcdefghijklmnopqrstvwuxyz':
        tmp = s[:]
        tmp.insert(i,letter)
        if palindrom(tmp):
            printans(tmp)
            exit()

print('NA')

nooon nooon aa staats levvel deiffied rottor levvel levvel adda raceecar abccba deiffied lsdijfjidsl civvic nooon maddam lsdijfjidsl raddar deiffied reviver testtset adda aa rottor civvic abbba NA rottor abbba bab civvic cnonnpbnpptppgntggttggtngpptppnbpnnonc abcccba acca NA NA aa raceecar testtset raddar raddar maddam NA

#include <bits/stdc++.h>
using namespace std;
int main() {
  string s, ss, cc;
  cin >> s;
  for (int i = 0; i <= s.length(); i++) {
    for (char ch = 'a'; ch <= 'z'; ch++) {
      ss = s;
      cc = ch;
      ss.insert(i, cc);
      if (ss == string(ss.rbegin(), ss.rend())) {
        cout << ss << endl;
        return 0;
      }
    }
  }
  cout << "NA" << endl;
  return 0;
}


R = lambda:map(int, input().split())
n, m = R()
a = list(R())
p, f, sz =[], [], []
e = [[] for i in range(n)]
vis = [0] * n
ans = 0
def find(u):
    if f[u] != u:
        f[u] = find(f[u])
    return f[u]
for i in range(n):
    p.append([a[i], i])
    f.append(i)
    sz.append(1)
p.sort()
p.reverse()
for i in range(m):
    u, v = R()
    e[u - 1].append(v - 1)
    e[v - 1].append(u - 1)
for i in range(n):
    u = p[i][1]
    for v in e[u]:
        if (vis[v] and find(u) != find(v)):
            pu, pv = u, v
            if (sz[f[u]] > sz[f[v]]):
                pu, pv = pv, pu
            ans += p[i][0] * sz[f[pu]] * sz[f[pv]]
            sz[f[pv]] += sz[f[pu]]
            f[f[pu]] = f[pv]
    vis[u] = 1
print("%.6f" %(2. * ans / n / (n - 1)))

3 2 1 2 3 1 2

I hope these sample inputs are helpful! Let me know if you have any questions or need further assistance.

#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[100005], num[100005];
int family[100005];
double ans = 0;
struct node {
  int le, ri;
  int quan;
} edge[100005];
bool comp(node xx, node yy) { return xx.quan > yy.quan; }
int Find(int x) { return family[x] == x ? x : family[x] = Find(family[x]); }
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1; i <= n; ++i) {
    family[i] = i;
    num[i] = 1;
  }
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d", &edge[i].le, &edge[i].ri);
    edge[i].quan = min(a[edge[i].le], a[edge[i].ri]);
  }
  sort(edge + 1, edge + m + 1, comp);
  for (int i = 1; i <= m; ++i) {
    int le_f = Find(edge[i].le);
    int ri_f = Find(edge[i].ri);
    if (le_f == ri_f) continue;
    ans += (double)(num[le_f]) * (double)(num[ri_f]) * (double)(edge[i].quan);
    family[le_f] = ri_f;
    num[ri_f] += num[le_f];
  }
  printf("%lf\n", ans * 2 / (double)(n) / (double)(n - 1));
  return 0;
}


#!/usr/bin/python3

def readln(): return tuple(map(int, input().split()))

n, = readln()
d = readln()
a, b = readln()
print(sum(d[a - 1:b - 1]))

#include <bits/stdc++.h>
using namespace std;
int N, a, b;
int arr[110];
int total = 0;
int main() {
  cin >> N;
  for (int i = 1; i <= N - 1; i++) {
    cin >> arr[i];
  }
  cin >> a >> b;
  for (int i = a; i <= b - 1; i++) {
    total = total + arr[i];
  }
  cout << total << endl;
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//package javaapplication1;

//import java.util.Scanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   StringTokenizer st=new StringTokenizer(br.readLine());
     int n=Integer.parseInt(st.nextToken()),k=Integer.parseInt(st.nextToken()),sum=0;
    int[] arr=new int[n+1];
    st=new StringTokenizer(br.readLine());
    for(int i=1;i<=n;i++){
        arr[i]=Integer.parseInt(st.nextToken());
        sum+=arr[i];
    }
    int ans=0,mn=Integer.MIN_VALUE;
    for(int i=1;i<=k;i++)
    {
        int temp=0;
        for(int j=i;j<=n;j+=k){
            temp+=arr[j];
        }
        if(sum-temp>mn){
            ans=i;
            mn=sum-temp;
        }
    }
        System.out.println(ans);

}
static class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br=new BufferedReader(new InputStreamReader(System.in));
        }
        String next(){
            while(st==null&&!st.hasMoreElements()){
                try{
                    st=new StringTokenizer(br.readLine());
                }
                catch (IOException e){
                }
            }
            return st.nextToken();
        }
        int nextInt(){
            return Integer.parseInt(next());
        }
        double nextDouble(){
            return Double.parseDouble(next());
        }
        long nextLong(){
            return Long.parseLong(next());
        }
        String nextLine(){
            String str="";
            try{
                str=br.readLine();
            }
            catch (IOException e){
            }
            return str;
        }
}

}

n,k = map(int, input().split())
t = list(map(int, input().split()))
current_sum = None
flag = 1
for i in range(k):
    if current_sum == None or sum(t[i :: k]) < current_sum:
        current_sum = sum(t[i :: k])
        flag = i+1
print(flag)
#print(min((sum(t[i :: k]), i) for i in range(k))[1] + 1)


# written with help of editorial
n, m = map(int, input().split())
a = list(map(int, input().split()))

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

g = 0
for x in a:
    g = gcd(g, x - 1)

answer = 0

def process(x):
    global answer
    if x % 2 == 0:
        return 0
    for i in range(30):
        v = 2 ** i * x
        if v > m:
            break
        answer += m - v

for i in range(1, g + 1):
    if i * i > g:
        break
    if g % i:
        continue
    process(i)
    if i * i != g:
        process(g // i)

print(answer)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;

public class E {
	BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter out;

    int gcd(int x, int y) {
		if (y == 0) {
			return x;
		}
		return gcd(y, x % y);
	}

    int[] getDivisors(int x){
    	int sqrt = (int) Math.sqrt(x);
    	int[] ret = new int[ 2*sqrt +1];
    	int ret_size = 0;

    	for(int i = 1; i <= sqrt; i++){
			if( x % i == 0){
				ret[ret_size++] = i;
				if( i != x/i)
					ret[ret_size++] = x/i;
			}
		}
    	ret = Arrays.copyOf(ret, ret_size);
    	return ret;
    }

	public void solve() throws IOException {
		int N = nextInt();
		int M = nextInt();
		int d = nextInt()-1;
		for(int i = 0; i < N-1; i++)
			d = gcd(d, nextInt()-1);

		long ans = 0;
		int[] divisors = getDivisors(d);
		HashSet<Integer> used = new HashSet<Integer>();
		for(int i = 0; i < divisors.length; i++){
			for(int j = divisors[i]; j <= M; j*=2){
				if( !used.contains(j)){
					ans += (M-j);
					used.add(j);
				}
			}
		}
		out.println( ans );
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new E().run();
	}

	public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            out = new PrintWriter(System.out);
            solve();
            reader.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

}


from sys import stdin
import sys

tt = int(stdin.readline())

for loop in range(tt):

    n = int(stdin.readline())
    s = stdin.readline()[:-1]

    if ("<" not in s) or (">" not in s):
        print (n)
        continue

    ans = 0
    for i in range(n):
        if s[(i-1)%n] == "-" or s[i] == "-":
            ans += 1

    print (ans)

#include <bits/stdc++.h>
using namespace std;
void solver(void);
long long int MOD = 1e9 + 7;
double pi = 2 * acos(0.0);
int main() {
  cin.tie(NULL);
  ios_base::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t--) solver();
}
void solver(void) {
  long long int n;
  cin >> n;
  string str;
  cin >> str;
  bool cycle = true;
  long long int indx = str.find('<');
  if (indx != string ::npos) {
    for (long long int i = 0; i < n; i++) {
      if (str[i] == '>') cycle = false;
    }
  }
  long long int indx1 = str.find('>');
  if (indx1 != string ::npos) {
    for (long long int i = 0; i < n; i++) {
      if (str[i] == '<') cycle = false;
    }
  }
  if (cycle) {
    cout << n << "\n";
    return;
  } else {
    long long int cnt = 0;
    for (long long int i = 0; i < n; i++) {
      if (i == 0) {
        if (str[0] == '-' || str[n - 1] == '-') cnt++;
      } else {
        if (str[i - 1] == '-' || str[i] == '-') cnt++;
      }
    }
    cout << cnt << "\n";
  }
}


import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Prac{
    static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        public InputReader(InputStream st) {
            this.stream = st;
        }
        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int ni() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public long nl() {
            int c = read();
            while (isSpaceChar(c)) {
            c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public int[] nia(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public int[] nia1(int n) {
            int a[] = new int[n+1];
            for (int i = 1; i <=n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public long[] nla(int n) {
            long a[] = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public long[] nla1(int n) {
            long a[] = new long[n+1];
            for (int i = 1; i <= n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public Long[] nLa(int n) {
            Long a[] = new Long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public Long[] nLa1(int n) {
            Long a[] = new Long[n+1];
            for (int i = 1; i <= n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public Integer[] nIa(int n) {
            Integer a[] = new Integer[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public Integer[] nIa1(int n) {
            Integer a[] = new Integer[n+1];
            for (int i = 1; i <= n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public String rs() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                    c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }
        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }
        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
    }
    public static class Key {
        private final int x, y;
        public Key(int x, int y) {
            this.x = x; this.y = y;
        }
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Key)) return false;
            Key key = (Key) o;
            return x == key.x && y == key.y;
        }
        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }
    static class Pair{
            int x,y;
            Pair(int a,int b){
                    x=a;y=b;
            }
//            @Override
//            public int compareTo(Pair p) {
//                    if(x==p.x) return y-p.y;
//                    return x-p.x;
//            }
    }
    static void shuffleArray(long temp[]){
        int n = temp.length;
        Random rnd = new Random();
        for(int i=0; i<n; ++i){
            long tmp = temp[i];
            int randomPos = i + rnd.nextInt(n-i);
            temp[i] = temp[randomPos];
            temp[randomPos] = tmp;
        }
    }
    static int gcd(int a,int b){ return b==0?a:gcd(b,a%b);}
    //static long lcm(long a,long b){return (a/gcd(a,b))*b;}
    static PrintWriter w = new PrintWriter(System.out);
    static long mod1=998244353L,mod=1000000007;
    //static int r[]={0,1,0,-1}, c[]={1,0,-1,0};
    static int[] nextG(int arr[]){
        int n = arr.length;
        Stack<Integer> s = new Stack<>();
        int ng[] = new int[n];
        for(int i = 0 ; i < n ; i++){
            while(!s.isEmpty() && arr[s.peek()] <= arr[i]){
                ng[s.pop()] = i;
            }
            s.add(i);
        }
        while(!s.isEmpty()){
            ng[s.pop()] = n;
        }
        return ng;
    }
    static int[] nextS(int arr[]){
        int n = arr.length;
        Stack<Integer> s = new Stack<>();
        int ns[] = new int[n];
        for(int i = 0 ; i < n ; i++){
            while(!s.isEmpty() && arr[s.peek()] >= arr[i]){
                ns[s.pop()] = i;
            }
            s.add(i);
        }
        while(!s.isEmpty()){
            ns[s.pop()] = n;
        }
        return ns;
    }
    static int[] prevG(int arr[]){
        int n = arr.length;
        Stack<Integer> s = new Stack<>();
        int pg[] = new int[n];
        for(int i = n-1 ; i >= 0 ; i--){
            while(!s.isEmpty() && arr[s.peek()] <= arr[i]){
                pg[s.pop()] = i;
            }
            s.add(i);
        }
        while(!s.isEmpty()){
            pg[s.pop()] = -1;
        }
        return pg;
    }
    static int[] prevS(int arr[]){
        int n = arr.length;
        Stack<Integer> s = new Stack<>();
        int ps[] = new int[n];
        for(int i = n-1 ; i >= 0 ; i--){
            while(!s.isEmpty() && arr[s.peek()] >= arr[i]){
                ps[s.pop()] = i;
            }
            s.add(i);
        }
        while(!s.isEmpty()){
            ps[s.pop()] = -1;
        }
        return ps;
    }
    public static void main(String [] args){
        InputReader sc=new InputReader(System.in);

        int n = sc.ni();
        int arr [] = sc.nia(n);
        int ng[] = nextG(arr);
        int ns [] = nextS(arr);
        int pg[] = prevG(arr);
        int ps[] = prevS(arr);
        int ans[]=new int[n];

        Arrays.fill(ans,10000000);
        ans[n-1] = 0;
        for(int i = n -1 ; i >= 0 ; i --){
            if(ns[i] != n){
                ans[i] = Math.min(ans[i] , ans[ns[i]]+1);
            }
            if(ng[i] != n){
                ans[i] = Math.min(ans[i] , ans[ng[i]]+1);
            }
            if(pg[i] != -1){
                ans[pg[i]] = Math.min(ans[pg[i]] , ans[i]+1);
            }
            if(ps[i] != -1){
                ans[ps[i]] = Math.min(ans[ps[i]] , ans[i]+1);
            }
        }

        w.println(ans[0]);
        w.close();
    }
}