import org.omg.PortableServer.AdapterActivator;

import java.io.*;
import java.lang.reflect.Array;
import java.net.CookieHandler;
import java.util.*;
import java.math.*;
import java.lang.*;
import java.util.concurrent.LinkedBlockingDeque;

import static java.lang.Math.*;

public class TaskA implements Runnable {
    long m = (int)1e9+7;
    PrintWriter w;
    InputReader c;
    public void run() {
        c = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int n = c.nextInt();
        int a[] = scanArrayI(n);
        int maxtime = Integer.MAX_VALUE,ind = -1;
        for(int i=0;i<n;i++){
            int time = Integer.MAX_VALUE;
            if(a[i]<i+1)
                time = i;
            else{
                time = (int)ceil((a[i] - i)/(double)n) * n + i;
            }
            if(time<maxtime){
                maxtime = time;
                ind = i;
            }
        }
        w.println(ind+1);
        w.close();
    }
    static long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    public static void sortbyColumn(int arr[][], int col){
        Arrays.sort(arr, new Comparator<int[]>()
        {
            public int compare(int[] o1, int[] o2){
                return(Integer.valueOf(o1[col]).compareTo(o2[col]));
            }
        });

    }
    public static class DJSet {
        public int[] upper;

        public DJSet(int n) {
            upper = new int[n];
            Arrays.fill(upper, -1);
        }

        public int root(int x) {
            return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
        }

        public boolean equiv(int x, int y) {
            return root(x) == root(y);
        }

        public boolean union(int x, int y) {
            x = root(x);
            y = root(y);
            if (x != y) {
                if (upper[y] < upper[x]) {
                    int d = x;
                    x = y;
                    y = d;
                }
                upper[x] += upper[y];
                upper[y] = x;
            }
            return x == y;
        }
    }
    public static int[] radixSort(int[] f)    {
        int[] to = new int[f.length];
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;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 < f.length;i++)b[1+(f[i]>>>16)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        return f;
    }
    public void printArray(int[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    public int[] scanArrayI(int n){
        int a[] = new int[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextInt();
        return a;
    }
    public long[] scanArrayL(int n){
        long a[] = new long[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextLong();
        return a;
    }
    public void printArray(long[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        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 String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public 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;
        }

        public 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;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            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 boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new TaskA(),"TaskA",1<<26).start();
    }
}


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

public class Main {
  static Scanner in = new Scanner(System.in);
  static PrintWriter out = new PrintWriter(System.out);

  public static void main(String[] args) {
    int n = in.nextInt();
    int m = in.nextInt();
    long boyMax = 0;
    int NBoyMax = 0;

    long sweets = 0;
    TreeSet<Long> boyMember = new TreeSet<>();
    for (int i = 0; i < n; i++) {
      long input = in.nextLong();
      boyMember.add(input);
      if (boyMax < input) {
        boyMax = input;
        NBoyMax = 1;
      } else if (boyMax == input) NBoyMax++;
      sweets += (input * m);
    }

    long smallestGirl = (long) 1e8 + 1;
    long sum = 0;
    for (int i = 0; i < m; i++) {
      long input = in.nextLong();
      sum += input;
      if (smallestGirl > input) smallestGirl = input;
    }

    if (smallestGirl < boyMember.last()) {
      out.println(-1);
    } else if (smallestGirl == boyMember.last()) {
      sweets += sum - boyMember.last() * m;
      out.println(sweets);
    } else {

      if (NBoyMax > 1) {
        sweets += sum - boyMember.last() * m;
        out.println(sweets);
      } else {
        Object[] boyList = boyMember.toArray();
        if (boyList.length > 1) {
          long boy = 0;
          boy = (long)boyList[boyList.length - 2];
          sweets += (sum - smallestGirl - boyMember.last() * (m - 1));
          sweets += (smallestGirl - boy);
          out.println(sweets);
        } else {
          out.println(-1);
        }
      }
    }

    in.close();
    out.close();
  }
}


import java.util.*;
import java.math.*;
public class Split {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n= sc.nextInt();
		int k= sc.nextInt();
		int a[] = new int[n];
		int d[] = new int[n-1];
		for(int i=0;i<n;i++) {
			a[i] = sc.nextInt();
			if(i>0)
				d[i-1] = a[i-1] - a[i];
		}
		Arrays.sort(d);
		int t = 0;
		for(int i=0;i<k-1;i++)
			t += d[i];
		System.out.println(a[n-1]-a[0]+t);
	}

}


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

public class RGBSubstring {
    public static void main(String[] args) {
        FastScanner scanner = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        int Q = scanner.nextInt();
        while(Q-->0) {
            int N = scanner.nextInt();
            int K = scanner.nextInt();
            String s1 = "RGB";
            String s2 = "GBR";
            String s3 = "BRG";
            char[] arr = scanner.next().toCharArray();
            int[] cnts = new int[3];
            for(int i = 0; i < K; i++) {
                int ind = i % 3;
                if (arr[i] != s1.charAt(ind)) cnts[0]++;
                if (arr[i] != s2.charAt(ind)) cnts[1]++;
                if (arr[i] != s3.charAt(ind)) cnts[2]++;
            }
            int ans = Math.min(Math.min(cnts[0], cnts[1]), cnts[2]);
            for(int i = K; i < N; i++) {
                int ind = (K-1)%3;
                int[] nextCnts = new int[3];
                nextCnts[1] = cnts[0];
                nextCnts[2] = cnts[1];
                nextCnts[0] = cnts[2];
                if ('R' != arr[i-K]) nextCnts[1]--;
                if ('G' != arr[i-K]) nextCnts[2]--;
                if ('B' != arr[i-K]) nextCnts[0]--;
                if (arr[i] != s1.charAt(ind)) nextCnts[0]++;
                if (arr[i] != s2.charAt(ind)) nextCnts[1]++;
                if (arr[i] != s3.charAt(ind)) nextCnts[2]++;
                cnts = nextCnts;
                for(int j = 0; j < 3; j++) ans = Math.min(ans, cnts[j]);
            }
            out.println(ans);
        }
        out.flush();
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

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

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

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

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

        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
    }
}


import java.util.Scanner;

public class NickAndArray {
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		 int array[]=new int[n];
		 int max=Integer.MAX_VALUE;
		 int index=0;
		 for(int i=0;i<n;i++)
		 {
			 int k=sc.nextInt();
			 array[i]=k;
			 if(array[i]>=0)
			 {
				 array[i]=-array[i]-1;
			 }
			 if(array[i]<max)
			 {
				 max=array[i];
				 index=i;

			 }
		 }
		 if(n%2!=0)
		 {
			 array[index]=-array[index]-1;
		 }
		 for(int i=0;i<n;i++)
		 {
			 System.out.print(array[i]+" " );
		 }
	}

}


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

public class Solution {

	static boolean canWinFromOneMove(char []s,int k) {
		int prefix=0;
		int n=s.length;
		for(int i=0;i<n && s[i]==s[0];i++)
			prefix++;
		int suffix=0;
		for(int i=n-1;i>=0 && s[i]==s[n-1];i--)
			suffix++;

		return s[0]==s[n-1] && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n;

	}
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		int n=sc.nextInt(),k=sc.nextInt();
		char []s=sc.next().toCharArray();
		if(canWinFromOneMove(s, k)) {
			System.out.println("tokitsukaze");
			return;
		}
		int []suff=new int [n+1];
		suff[n-1]=1;
		for(int i=n-2;i>=0;i--) {
			suff[i]=1+(s[i+1]==s[i]?suff[i+1]:0);
		}
		for(int i=n-2;i>=0;i--)
			suff[i]=Math.max(suff[i], suff[i+1]);
		int max=0,curr=0;
		boolean draw=false;
		int ones=0;
		for(int i=0;i+k<=n;i++) {

			// one
			int prefix=ones==i?k+ones:max;
			int suffix=i+k==n?k:s[i+k]=='1' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k];
			char first=i==0?'1':s[0],last=i+k==n?'1':s[n-1];
			boolean zero=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n;
			// zero
			 prefix=ones==0?k+ones:max;
			 suffix=i+k==n?k:s[i+k]=='0' && suff[i+k]==n-(i+k)?k+suff[i+k]:suff[i+k];
			 first=i==0?'0':s[0];
			 last=i+k==n?'0':s[n-1];
			boolean one=first==last && prefix+suffix+k>=n || Math.max(prefix, suffix)+k>=n;
			if(!zero || !one) {
//				System.err.println(i+1);
				draw=true;
			}
			if(s[i]=='1')
				ones++;
			if(i>0 && s[i]==s[i-1] )
				curr++;
			else
				curr=1;
			max=Math.max(max, curr);
		}
		out.println(draw?"once again":"quailty");
		out.close();

	}

	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		Scanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		Scanner(String fileName) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(fileName));
		}

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

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

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

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

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

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

	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;

public class c {
	public static void main(String[] args) throws IOException {
		FastScanner in = new FastScanner(System.in);
		int n = in.nextInt(), m = in.nextInt();
		long bounty = in.nextInt(), increase = in.nextInt();
		int damage = in.nextInt();
		int[] mh = new int[n];
		int[] sh = new int[n];
		int[] reg = new int[n];
		long countKilled = 0;
		ArrayList<Event> es = new ArrayList<>();
		Event[] regen = new Event[n];
		for(int i=0;i<n;i++) {
			mh[i] = in.nextInt();
			sh[i] = in.nextInt();
			reg[i] = in.nextInt();
			if(sh[i] <= damage)
				countKilled++;
			if(reg[i] > 0) {
				int time = (damage+1 - sh[i]+reg[i]-1)/reg[i];
				if(time > 0 && mh[i] >= damage+1) {
					Event e2 = new Event(time, i, damage+1);
					regen[i] = e2;
					es.add(e2);
				}
			}
		}
		for(int i=0;i<m;i++) {
			Event e = new Event(in.nextInt(), in.nextInt()-1, in.nextInt());
			es.add(e);
			if(reg[e.e] > 0) {
				int time = (damage+1 - e.h+reg[e.e]-1)/reg[e.e];
				if(time > 0 && mh[e.e] >= damage+1) {
					Event e2 = new Event(e.t + time, e.e, damage+1);
					e.regen = e2;
					es.add(e2);
				}
			}
		}
		Collections.sort(es, (a,b) -> a.t-b.t);
		long ans = countKilled*bounty;
		int lastTime = 0;
		for(Event e : es) {
			if(e.t == -1) continue;
			if(regen[e.e] != e && regen[e.e] != null) {
				regen[e.e].t = -1;
				regen[e.e] = null;
			}
			if(lastTime != e.t) {
				ans = Math.max(ans, countKilled*(bounty+(e.t-1)*increase));
			}
			if(sh[e.e] <= damage)
				countKilled--;
			sh[e.e] = e.h;
			if(sh[e.e] <= damage)
				countKilled++;
			if(e.regen != null) {
				regen[e.e] = e.regen;
			}
			lastTime = e.t;
		}
		if(countKilled != 0) {
			if(increase > 0)
				ans = -1;
			else
				ans = Math.max(ans, countKilled*bounty);
		}
		System.out.println(ans);
	}
	static class Event {
		int t;
		int e;
		int h;
		Event regen;
		public Event(int tt, int ee, int hh) {
			t = tt;
			e = ee;
			h = hh;
		}
	}
	static class FastScanner {
	    BufferedReader br;
	    StringTokenizer st;
	    public FastScanner(InputStream i) {
	        br = new BufferedReader(new InputStreamReader(i));
	        st = new StringTokenizer("");
	    }
	    public String next() throws IOException {
	        if(st.hasMoreTokens())
	            return st.nextToken();
	        else
	            st = new StringTokenizer(br.readLine());
	        return next();
	    }
	    public int nextInt() throws IOException {
	        return Integer.parseInt(next());
	    }
	    public long nextLong() throws IOException {
	        return Long.parseLong(next());
	    }
	    public double nextDouble() throws IOException {
	        return Double.parseDouble(next());
	    }
	}
}


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

public class KingEscape {

    public static void main(String[] args) {
        Reader read = new Reader();

        int n = read.nextInt();
        int a1 = read.nextInt();
        int a2 = read.nextInt();
        int b1 = read.nextInt();
        int b2 = read.nextInt();
        int c1 = read.nextInt();
        int c2 = read.nextInt();

        if (b1 > a1 && b2 > a2 && c1 > a1 && c2 > a2)
            System.out.print("YES");
        else if (b1 > a1 && b2 < a2 && c1 > a1 && c2 < a2)
            System.out.print("YES");
        else if (b1 < a1 && b2 > a2 && c1 < a1 && c2 > a2)
            System.out.print("YES");
        else if (b1 < a1 && b2 < a2 && c1 < a1 && c2 < a2)
            System.out.print("YES");
        else
            System.out.print("NO");
    }

    private static class Reader {

        private final BufferedReader reader;
        private final String separator;
        private String ln;
        private String[] tokens;
        private int ptr;

        Reader(String separator, InputStream input) {
            this.reader = new BufferedReader(new InputStreamReader(input));
            this.separator = separator;
            this.ptr = -1;
        }

        Reader(String separator) { this(separator, System.in); }

        Reader() { this(" "); }

        String nextStr(){
            if (Objects.isNull(ln)) {
                try {
                    ln = reader.readLine();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
                if (Objects.nonNull(ln)) {
                    tokens = ln.split(separator);
                    ptr = 0;
                } else {
                    throw new NoSuchElementException("no next element");
                }

            } else if (ptr == tokens.length) {
                ln = null;
                tokens = null;
                ptr = -1;
                return nextStr();
            }

            return tokens[ptr++];
        }

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

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

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


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

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

    static class DConcatenatedMultiples {
        public void solve(int testNumber, ReaderFastIO in, PrintWriter out) {

            Map<Integer, Integer>[] mapMods = new HashMap[11];

            int n = in.nextInt();
            int k = in.nextInt();
            int[] a = in.readArrayInt(n);

            for (int i = 0; i < 11; i++) {
                mapMods[i] = new HashMap<>();
            }

            for (int i = 0; i < n; i++) {
                int pot = getPot(a[i]);
                mapMods[pot].put(a[i] % k, mapMods[pot].getOrDefault(a[i] % k, 0) + 1);
            }

            long ct = 0;

            for (int i = 0; i < n; i++) {

                int ownPot = getPot(a[i]);
                long suffix = a[i] * 10L;
                for (int j = 1; j <= 10; j++) {

                    int mod = (int) (suffix % k);
                    int comMod = (k - mod) % k;
                    int qt = mapMods[j].getOrDefault(comMod, 0);

                    if (j == ownPot && (a[i] % k) == comMod) {
                        qt--;
                    }

                    ct += qt;

                    suffix = (suffix * 10L) % k;
                }

            }

            out.println(ct);
        }

        public int getPot(int x) {

            int ct = 0;

            while (x != 0) {
                x /= 10;
                ct++;
            }

            return ct;
        }

    }

    static class ReaderFastIO {
        BufferedReader br;
        StringTokenizer st;

        public ReaderFastIO() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public ReaderFastIO(InputStream input) {
            br = new BufferedReader(new InputStreamReader(input));
        }

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

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

        public int[] readArrayInt(int n) {

            int[] array = new int[n];

            for (int i = 0; i < n; i++) {
                array[i] = nextInt();
            }

            return array;
        }

    }
}


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

public class Equator {
	public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
	public static StringTokenizer st;

	public static void main(String[] args) throws IOException {
		int n = nextInt();
		int[] a = intArray(n);

		long s = 0;
		for (int x : a)
			s += x;

		long m = 0;
		for (int i = 0; i < n; i++) {
			m += a[i];
			if (m*2 >= s) {
				System.out.println(i+1);
				return;
			}
		}
	}

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

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

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

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

	public static int[] intArray(int n) throws IOException {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = nextInt();
		return a;
	}

	public static int[][] intArray(int n, int m) throws IOException {
		int[][] a = new int[n][m];
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				a[i][j] = nextInt();
		return a;
	}

	public static long[] longArray(int n) throws IOException {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nextLong();
		return a;
	}
}


//package codeforces;

import java.util.Scanner;

public class Fingerprints {

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

		int[] code = new int[scanner.nextInt()];
		int[] prints = new int[scanner.nextInt()];

		for (int i = 0; i < code.length; i++) {
			code[i] = scanner.nextInt();
		}
		for (int i = 0; i < prints.length; i++) {
			prints[i] = scanner.nextInt();
		}
		for (int i = 0; i < code.length; i++) {
			for (int j = 0; j < prints.length; j++) {
				if (code[i] == prints[j]) {
					System.out.print(prints[j] + " ");
				}
			}
		}
		scanner.close();
	}

}


/*
Keep solving problems.
*/

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

public class CFA {
    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;
    private static long MOD = 1000L * 1000L * 1000L + 7;
    private static final int[] dx = {0, -1, 0, 1};
    private static final int[] dy = {1, 0, -1, 0};
    private static final String yes = "Yes";
    private static final String no = "No";

    int n;
    int m;
    char[][] mat;
    long base = 397;
    void solve() throws IOException {
        n = nextInt();
        m = nextInt();
        mat = new char[n][m];
        for (int i = 0; i < n; i++) {
            mat[i] = nextString().toCharArray();
        }

        int alpha = 26;
        long[] pow = new long[alpha];
        pow[0] = 1;
        for (int i = 1; i < alpha; i++) {
            pow[i] = pow[i - 1] * base % MOD;
        }

        long res = 0;
        for (int l = 0; l < m; l++) {
            //[l, r]
            long[] hash = new long[n];
            long[] mask = new long[n];
            for (int r = l; r < m; r++) {
                for (int i = 0; i < n; i++) {
                    hash[i] += pow[mat[i][r] - 'a'];
                    hash[i] %= MOD;
                    mask[i] = mask[i] ^ (1L << (mat[i][r] - 'a'));
                }

                int start = 0;
                while (start < n) {
                    if ((mask[start] & (mask[start] - 1)) != 0) {
                        start++;
                        continue;
                    }

                    int end = start;
                    List<Long> l1 = new ArrayList<>();
                    while (end < n && (mask[end] & (mask[end] - 1)) == 0) {
                        l1.add(hash[end]);
                        end++;
                    }

                    start = end;
                    res += manacher(l1);
                }
            }
        }

        outln(res);
    }

    long manacher(List<Long> arr) {
        int len = arr.size();
        long[] t = new long[len * 2 + 3];
        t[0] = -1;
        t[len * 2 + 2] = -2;
        for (int i = 0; i < len; i++) {
            t[2 * i + 1] = -3;
            t[2 * i + 2] = arr.get(i);
        }

        t[len * 2 + 1] = -3;
        int[] p = new int[t.length];
        int center = 0, right = 0;
        for (int i = 1; i < t.length - 1; i++) {
            int mirror = 2 * center - i;
            if (right > i) {
                p[i] = Math.min(right - i, p[mirror]);
            }

            // attempt to expand palindrome centered at i
            while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) {
                p[i]++;
            }

            // if palindrome centered at i expands past right,
            // adjust center based on expanded palindrome.
            if (i + p[i] > right) {
                center = i;
                right = i + p[i];
            }
        }

        long res = 0;
        for (int i = 0; i < 2 * len; i++) {
            int parLength = p[i + 2];
            if (i % 2 == 0) {
                res += (parLength + 1) / 2;
            }
            else {
                res += parLength / 2;
            }
        }

        return res;
    }

    void shuffle(int[] a) {
        int n = a.length;
        for(int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            int tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }
    long gcd(long a, long b) {
        while(a != 0 && b != 0) {
            long c = b;
            b = a % b;
            a = c;
        }
        return a + b;
    }
    private void outln(Object o) {
        out.println(o);
    }
    private void out(Object o) {
        out.print(o);
    }
    private void formatPrint(double val) {
        outln(String.format("%.9f%n", val));
    }
    public CFA() throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }
    public static void main(String[] args) throws IOException {
        new CFA();
    }

    public long[] nextLongArr(int n) throws IOException{
        long[] res = new long[n];
        for(int i = 0; i < n; i++)
            res[i] = nextLong();
        return res;
    }
    public int[] nextIntArr(int n) throws IOException {
        int[] res = new int[n];
        for(int i = 0; i < n; i++)
            res[i] = nextInt();
        return res;
    }
    public String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
            }
        }
        return st.nextToken();
    }
    public String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;
        }
    }
    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}


import java.util.*;
import java.io.*;
import java.math.*;
public class loser
{
    static class InputReader {
        public BufferedReader br;
        public StringTokenizer token;
        public InputReader(InputStream stream)
        {
            br=new BufferedReader(new InputStreamReader(stream),32768);
            token=null;
        }

        public String next()
        {
            while(token==null || !token.hasMoreTokens())
            {
                try
                {
                    token=new StringTokenizer(br.readLine());
                }
                catch(IOException e)
                {
                    throw new RuntimeException(e);
                }
            }
            return token.nextToken();
        }

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

        public long nextLong()
        {
            return Long.parseLong(next());
        }
    }
    static class card{
        int l;
        int r;
        public card(int ch,int i)
        {
            this.l=ch;
            this.r=i;
        }
    }
    static class sort implements Comparator<card>
    {
        public int compare(card o1,card o2)
        {
            if(o1.l!=o2.l)
                return (int)(o1.l-o2.l);
            else
                return (int)(o1.r-o2.r);
        }
    }
    static void shuffle(long a[])
    {
        List<Long> l=new ArrayList<>();
        for(int i=0;i<a.length;i++)
            l.add(a[i]);
        Collections.shuffle(l);
        for(int i=0;i<a.length;i++)
            a[i]=l.get(i);
    }

    /*static long gcd(long a,long b)
    {
    if(b==0)
    return a;
    else
    return gcd(b,a%b);
    }
    static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE;
    static boolean v[]=new boolean[101];
    static void dfs(Integer so,Set<Integer> s[]){
    if(!v[so.intValue()])
    {
    v[so]=true;
    for(Integer h:s[so.intValue()])
    {
    if(!v[h.intValue()])
    dfs(h,s);
    }
    }
    }
    static class Print{
    public PrintWriter out;
    Print(OutputStream o)
    {
    out=new PrintWriter(o);
    }
    }
    static int CeilIndex(int A[], int l, int r, int key)
    {
    while (r - l > 1) {
    int m = l + (r - l) / 2;
    if (A[m] >= key)
    r = m;
    else
    l = m;
    }

    return r;
    }

    static int LongestIncreasingSubsequenceLength(int A[], int size)
    {
    // Add boundary case, when array size is one
    int[] tailTable = new int[size];
    int len; // always points empty slot
    tailTable[0] = A[0];
    len = 1;
    for (int i = 1; i < size; i++) {
    if (A[i] < tailTable[0])
    // new smallest value
    tailTable[0] = A[i];

    else if (A[i] > tailTable[len - 1])
    // A[i] wants to extend largest subsequence
    tailTable[len++] = A[i];

    else
    // A[i] wants to be current end candidate of an existing
    // subsequence. It will replace ceil value in tailTable
    tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i];
    }
    return len;
    }*/
    /*static int binary(int n)
    {
    int s=1;
    while(n>0)
    {
    s=s<<1;
    n--;
    }
    return s-1;
    }
    static StringBuilder bin(int i,int n)
    {
    StringBuilder s=new StringBuilder();
    while(i>0)
    {
    s.append(i%2);
    i=i/2;
    }
    while(s.length()!=n)
    {
    s.append(0);
    }
    return s.reverse();
    }*/
    static boolean valid(int i,int j,int n,int m)
    {
        if(i<n && i>=0 && j<m && j>=0)
            return true;
        else
            return false;
    }

    public static void main(String[] args)
    {
        InputReader sc=new InputReader(System.in);
        int n=sc.nextInt();
        int s=sc.nextInt();
        card c[]=new card[n];
        for(int i=0;i<n;i++)
        {
            int x=sc.nextInt();
            int y=sc.nextInt();
            c[i]=new card(x,y);
        }
        Arrays.sort(c,new sort());
        int time=0;
        for(int i=n-1;i>=0;i--)
        {
            time+=s-c[i].l;
            if((c[i].r-time)>0)
            time+=c[i].r-time;
            s=c[i].l;
        }
        if(c[0].l!=0)
        time+=c[0].l;
        System.out.println(time);
    }
}


import java.io.*;
import java.lang.*;
import java.util.*;
import static java.lang.Integer.*;
import static java.lang.Long.*;
import static java.lang.Math.*;
import static java.lang.System.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;

public class Main {

    Main() throws IOException {
        String a = nextLine();
        String b = nextLine();
        long ans = 0;
        int s = 0;
        for (int i = 0; i < b.length() - a.length(); ++i) {
            s += b.charAt(i) == '1' ? 1 : 0;
        }

        for (int i = 0; i < a.length(); ++i) {
            s += b.charAt(i + b.length() - a.length()) == '1' ? 1 : 0;
            ans += a.charAt(i) == '1' ? b.length() - a.length() + 1 - s : s;
            s -= b.charAt(i) == '1' ? 1 : 0;
        }
        out.println(ans);
    }

    //////////////////////////////
    PrintWriter out = new PrintWriter(System.out, false);
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer stok = null;
    String nextLine() throws IOException {
        while (stok == null || !stok.hasMoreTokens()) {
            stok = new StringTokenizer(in.readLine());
        }
        return stok.nextToken();
    }

    public static void main(String args[]) throws IOException {
        if (args.length > 0) {
            setIn(new FileInputStream(args[0] + ".inp"));
            setOut(new PrintStream(args[0] + ".out"));
        }
        Main solver = new Main();
        solver.out.flush();  //  could be replace with a method, but nah, this is just competitive programming :p
    }
}


import java.util.*;

public class vas2 {
    public static void main( String[] args ) {
	Scanner in = new Scanner( System.in );
	int n = in.nextInt();
	String st = in.next();
	int[] a = new int[n];
	for ( int i = 0; i < n; i++ )
	    a[i] = st.charAt( i ) - 48;
	boolean c = false;
	for ( int i = 1; !c && i < n; i++ ) {
	    int s = 0;
	    for ( int j = 0; j < i; j++ )
		s += a[j];
	    int t = 0;
	    for ( int j = i; j < n; j++ ) {
		t += a[j];
		if ( t > s )
		    if ( t - a[j] != s )
			break;
		    else
			t = a[j];
	    }
	    if ( t == s )
		c = true;
	}
	System.out.println( c ? "YES" : "NO" );
    }
}


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

/**
 * @author Don Li
 */
public class LogicalExpression {

    int N = 256;

    void solve() {
        Expression[] E = new Expression[N];
        for (int i = 0; i < N; i++) E[i] = new Expression();

        E[Integer.parseInt("00001111", 2)].update_f("x");
        E[Integer.parseInt("00110011", 2)].update_f("y");
        E[Integer.parseInt("01010101", 2)].update_f("z");

        for (int l = 2; l < 40; l++) {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    if (E[i].e != null && E[j].t != null && E[i].e.length() + E[j].t.length() + 1 == l) {
                        E[i | j].update_e(E[i].e + '|' + E[j].t);
                    }
                    if (E[i].t != null && E[j].f != null && E[i].t.length() + E[j].f.length() + 1 == l) {
                        E[i & j].update_t(E[i].t + '&' + E[j].f);
                    }
                }
                if (E[i].f != null) E[i ^ (N - 1)].update_f('!' + E[i].f);
            }
        }

        String[] res = new String[N];
        for (int i = 0; i < N; i++) res[i] = E[i].calc_best();

        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            int x = Integer.parseInt(in.nextToken(), 2);
            out.println(res[x]);
        }
    }

    static class Expression {
        String e, t, f;

        Expression() {
        }

        public Expression(String e, String t, String f) {
            this.e = e;
            this.t = t;
            this.f = f;
        }

        String calc_best() {
            String best = e;
            if (compare(best, t) > 0) best = t;
            if (compare(best, f) > 0) best = f;
            return best;
        }

        void update_e(String ne) {
            if (e == null || compare(e, ne) > 0) {
                e = ne;
                update_f('(' + e + ')');
            }
        }

        void update_t(String nt) {
            if (t == null || compare(t, nt) > 0) {
                t = nt;
                update_e(t);
            }
        }

        void update_f(String nf) {
            if (f == null || compare(f, nf) > 0) {
                f = nf;
                update_t(f);
            }
        }

        int compare(String a, String b) {
            if (a.length() != b.length()) return Integer.compare(a.length(), b.length());
            return a.compareTo(b);
        }
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new LogicalExpression().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

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

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

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

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


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

public class FirstClass {

	public static void main(String[] args)throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		int n = Integer.parseInt(br.readLine());

		int arr[] = new int [n];

		StringTokenizer st1 = new StringTokenizer(br.readLine());

		for(int i = 0 ; i < n ; i++)
		{
			arr[i] = Integer.parseInt(st1.nextToken());
		}

		int max = -1;
		boolean flag = true;

		for(int i = 0 ; i < n ; i++)
		{
			if(arr[i] > max+1)
			{
				flag = false;
				out.println(i+1);
				break;
			}
			else
			{
				max = Math.max(max, arr[i]);
			}
		}

		if(flag)
			out.println(-1);

		out.flush();
		out.close();
	}

}


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

public class AnnoyingPresent {

	//UPSOLVED
	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
        long n = Long.parseLong(st.nextToken()) , m = Long.parseLong(st.nextToken());

        long sum = 0;

        for(int i=0;i<m;i++){
        	StringTokenizer st1 = new StringTokenizer(br.readLine());
            sum+= n* Long.parseLong(st1.nextToken());
            Long a= Long.parseLong(st1.nextToken());
            if(a < 0){
                if(n % 2 == 0)
                    sum += n*n / 4*a;
                else{
                    sum += (n/2) * (n/2+1) * a;
                }
            }
            else
                sum += (a*(n) * (n-1) / 2);

        }
        System.out.println((double)sum/n);
	}

}


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

		public class codeforces
		{
			public static void main(String[] args)
			{
				InputReader in = new InputReader(System.in);
				PrintWriter pw = new PrintWriter(System.out);

				int n = in.nextInt();
				long U = in.nextLong();
				long[] E = new long[n];
				double max = -1;

				for(int i=0;i<n;i++)
					E[i] = in.nextLong();

				for(int k=1;k<n-1;k++)
				{
					int i = k + 1, j = n - 1, mid = 0;
					double T = 0;

					while(i < j)
					{
						mid = (int)Math.ceil((double)(i+j)/2);

						if(E[mid] - E[k-1] <= U)
							i = mid;
						else
							j = mid - 1;
					}

					j = k;
					k = i;
					i = j - 1;

					T = E[k] - E[j];
					T /= E[k] - E[i];

					if(E[k] - E[i] <= U)
						max = Math.max(max, T);

					k = j;
				}

				pw.println(max);

				pw.flush();
				pw.close();
			}

		/*	public static void DFS(int sourse)
			{
				int count = 0;
				visited[sourse] = true;

				for(int u : adj[sourse])
				{
					if(!visited[u])
					{
						DFS(u);
					}
				}

			}*/

			public static ArrayList Divisors(long n)
			{
			    ArrayList<Long> div = new ArrayList<>();

			    for (long i=1; i<=Math.sqrt(n); i++)
			    {
			        if (n%i == 0)
			        {
			        	div.add(i);

			            if(n/i != i)
			            	div.add(n/i);
			        }
			    }
			    return div;
			}

			public static int BinarySearch(long[] a, long k)
			{
				int n = a.length;
				int i = 0, j = n-1;
				int mid = 0;

				if(k < a[0])
					return 0;
				else if(k >= a[n-1])
					return n;
				else
				{
					while(j - i > 1)
					{
						mid = (i+j)/2;

						if(k >= a[mid])
							i = mid;
						else
							j = mid;
					}
				}

				return i+1;
			}
			public static long GCD(long a,long b)
			{
				if(b==0)
					return a;
				else
					return GCD(b,a%b);
			}

			static class pair implements Comparable<pair>
			{
				Integer x, y;
				pair(int x,int y)
				{
					this.x=x;
					this.y=y;
				}

				public int compareTo(pair o) {
					int result = x.compareTo(o.x);
					if(result==0)
						result = y.compareTo(o.y);

					return result;
				}

				public String toString()
				{
					return x+" "+y;
				}

				public boolean equals(Object o)
				{
					if (o instanceof pair)
				    {
						pair p = (pair)o;
						return p.x - x == 0 && p.y - y == 0 ;
					}
					return false;
				}

				public int hashCode()
				{
					return new Long(x).hashCode()*31 + new Long(y).hashCode();
				}
			}

			static class InputReader
			{

				private final InputStream stream;
				private final byte[] buf = new byte[8192];
				private int curChar, snumChars;
				private SpaceCharFilter filter;

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

				public int snext()
				{
					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 nextInt()
			    {
					int c = snext();
					while (isSpaceChar(c))
					{
						c = snext();
					}
					int sgn = 1;
					if (c == '-')
				    {
						sgn = -1;
						c = snext();
					}
					int res = 0;
					do
					{
						if (c < '0' || c > '9')
							throw new InputMismatchException();
						res *= 10;
						res += c - '0';
						c = snext();
					} while (!isSpaceChar(c));
					return res * sgn;
				}

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

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

				public String readString()
			    {
					int c = snext();
					while (isSpaceChar(c))
					{
						c = snext();
					}
					StringBuilder res = new StringBuilder();
					do
					{
						res.appendCodePoint(c);
						c = snext();
					} while (!isSpaceChar(c));
					return res.toString();
				}

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

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

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

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

			static class CodeX {
	        public static void sort(long arr[]) {
	            merge_sort(arr, 0, arr.length - 1);
	        }

	        private static void merge_sort(long A[], long start, long end) {
	            if (start < end) {
	                long mid = (start + end) / 2;
	                merge_sort(A, start, mid);
	                merge_sort(A, mid + 1, end);
	                merge(A, start, mid, end);
	            }

	        }

	        private static void merge(long A[], long start,long mid, long end) {
	            long p = start, q = mid + 1;
	            long Arr[] = new long[(int)(end - start + 1)];
	            long k = 0;

	            for (int i = (int)start; i <= end; i++) {
	                if (p > mid)
	                    Arr[(int)k++] = A[(int)q++];

	                else if (q > end)
	                    Arr[(int)k++] = A[(int)p++];

	                else if (A[(int)p] < A[(int)q])
	                    Arr[(int)k++] = A[(int)p++];

	                else
	                    Arr[(int)k++] = A[(int)q++];
	            }
	            for (int i = 0; i < k; i++) {
	                A[(int)start++] = Arr[i];
	            }

	        }

	    }
		}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;

 import java.util.*;
public class Main
{
static Graph graph[];
	public static void add_edge(int u,int v)
	{
		graph[u].adj.add(graph[v]);
		graph[v].adj.add(graph[u]);
	}
	public static void dfs(int index)
	{
		Graph z=graph[index];
		z.vis=1;Graph v;
		for( int i=0;i<z.adj.size();i++)
		{
			v=z.adj.get(i);
			if(v.vis==0)
			{
				v.dist=z.dist+1;
				v.parent=z.val;
				dfs(v.val);
			}
		}

	}
    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)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args)
    {
        FastReader sc=new FastReader();
		int n=sc.nextInt();
		Pair arr[]=new Pair[n];
		Pair pref[]=new Pair[n];
		Pair suff[]=new Pair[n];
		for( int i=0;i<n;i++)
		{
			long u=sc.nextLong();
			long v=sc.nextLong();
			arr[i]=new Pair(u,v);
			pref[i]=new Pair(0,0);
			suff[i]=new Pair(0,0);
		}
		pref[0].x=arr[0].x;
		pref[0].y=arr[0].y;
		for( int i=1;i<n;i++)
		{
			pref[i].x=(long)Math.max(pref[i-1].x,arr[i].x);
			pref[i].y=(long)Math.min(pref[i-1].y,arr[i].y);
		}
		suff[n-1].x=arr[n-1].x;
		suff[n-1].y=arr[n-1].y;
		for( int i=n-2;i>=0;i--)
		{
			suff[i].x=(long)Math.max(suff[i+1].x,arr[i].x);
			suff[i].y=(long)Math.min(suff[i+1].y,arr[i].y);
		}
		long max=Long.MIN_VALUE;
		long ans=0;

		for( int i=0;i<n;i++)
		{
			long val=Long.MAX_VALUE;
			long val1=Long.MAX_VALUE;

			if(i!=0&&i!=n-1)
			{
				 val=(long)Math.min(pref[i-1].y,suff[i+1].y)-(long)Math.max(pref[i-1].x,suff[i+1].x);

			}
			else if(i!=n-1)
			{
				val=suff[i+1].y-suff[i+1].x;
			}
			else
				val=pref[i-1].y-pref[i-1].x;

			ans=val;
			if(ans<0)
				ans=0;
			max=(long)Math.max(ans,max);
		}
		System.out.println(max);

    }
}
class mycomparator implements Comparator<Graph>
{
	public int compare(Graph a, Graph b)
	{
		return b.dist-a.dist;
	}
}
class Graph
{
	int vis,col,val;int parent;int deg;int dist;
	ArrayList<Graph> adj;
	Graph(int val)
	{
		vis=0;
		col=-1;
		adj=new ArrayList<>();
		parent=-1;
		this.val=val;
		deg=0;
		dist=-1;
	}
}
class Pair
{
	long x,y;
	Pair( long x, long y)
	{
		this.x=x;
		this.y=y;
	}
}


import java.util.*;

public class ehab4 {
    public static void main( String[] args ) {
        Scanner in = new Scanner( System.in );
	int a = 0, b = 0;
	System.out.println( "? 0 0 " );
	System.out.flush();
	int c = in.nextInt();
	for ( int i = 29; i >= 0; i-- ) {
	    System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b );
	    System.out.flush();
	    int q1 = in.nextInt();
	    System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) );
	    System.out.flush();
	    int q2 = in.nextInt();
	    if ( q1 == q2 ) {
		if ( c == 1 )
		    a += ( 1 << i );
		else if ( c == -1 )
		    b += ( 1 << i );
		c = q1;
	    }
	    else if ( q1 == -1 ) {
		a += ( 1 << i );
		b += ( 1 << i );
	    }
	    else if ( q1 == -2 )
		return;
	}
	System.out.println( "! " + a + " " + b );
	System.out.flush();
    }
}

1088_D. Ehab and another another xor problem


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

public class Main {
    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        //Scanner sc = new Scanner();
        Reader in = new Reader();
        Main solver = new Main();
        solver.solve(out, in);
        out.flush();
        out.close();

    }

    static int INF = (int)1e5*4*4+5;
    static int maxn = (int)1e5*2+1;
    static int mod=(int)1e9+7 ;
    static int n,m,k,t,q,x,a,b,y;

    static ArrayList<Integer> adj[];
    static int[] dist,parent,back;
    static boolean[] vis,vist;
    static int root=0,ans=1;

    void solve(PrintWriter out, Reader in) throws IOException{
        n = in.nextInt();

        if(n==1) {out.println(1);return;}
        adj = new ArrayList[n+1];
        for(int i=1;i<=n;i++)
            adj[i] = new ArrayList<Integer>();

        int u,v;
        for(int i=0;i<n-1;i++){
            u = in.nextInt();
            v = in.nextInt();

            adj[u].add(v);
            adj[v].add(u);
        }

        vist = new boolean[n+1];
        vis = new boolean[n+1];
        vist[1] =true;
        makeroot(1);

        parent = new int[n+1];
        dist = new int[n+1];
        back = new int[n+1];

        dfs(root,0);
        calcdist(root);

        vist = new boolean[n+1];
        vis = new boolean[n+1];
        vist[root] =true;

        PriorityQueue<Node> pq = new PriorityQueue<Node>();
        for(int i=1;i<=n;i++){
            if(i!=root) pq.add(new Node(i,dist[i]));
        }

        Node elm;
        int rt = root;
        out.print(1);

        makeroot(root);
        removeNodes(root,rt);
        ans+=dist[rt];
        out.print(" "+ans);
        int itr=2;
        for(int i=2;i<=n;i++){

            elm = pq.remove();
            if(vis[elm.idx]) continue;
            removeNodes(back[elm.idx],elm.idx);
            ans += elm.dist+1;
            out.print(" "+ans);
            itr++;
        }
        for(int i=itr;i<n;i++)
            out.print(" "+ans);
        out.println();
    }

    //<>

    static class Node implements Comparable<Node>{
        int dist,idx;

        Node(int idx,int dist){
            this.idx = idx;
            this.dist = dist;
        }

        public int compareTo(Node o) {
            return o.dist-this.dist;
        }
    }

    static void removeNodes(int s,int e){
        vis[s]=true;
        while(s!=e){
            vis[s] = true;
            s = parent[s];
        }
        vis[s]=true;
        return;
    }

    static int calcdist(int s){
        int res=0;
        int tmp=0;
        for(int e:adj[s]){
            if(e!=parent[s]){
                tmp= calcdist(e);
                if(1+tmp>res){
                    res = 1+tmp;
                    back[s] = back[e];
                }
            }
        }

        if(res==0) back[s]=s;
        return dist[s] = res;
    }

    static void dfs(int s,int p){
        for(int e:adj[s]){
            if(e!=p){
                parent[e]=s;
                dfs(e,s);
            }
        }
        return;
    }

    static void makeroot(int s){
        Queue<Integer> q = new LinkedList<>();
        q.add(s);

        int elm=0;
        while(q.size()!=0){
            elm = q.remove();
            for(int e:adj[elm]){
                if(!vist[e]){
                    vist[e]=true;
                    q.add(e);
                    root = e;
                }
            }
        }
        return;
    }

    static class Reader {

    private InputStream mIs;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public Reader() {
        this(System.in);
    }

    public Reader(InputStream is) {
        mIs = is;
    }

    public int read() {
        if (numChars == -1) {
            throw new InputMismatchException();

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

    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 String next() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
        }
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

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

    public 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;
    }

    public 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;
    }

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

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

    }
}


import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.min;
import static java.lang.System.exit;

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

public class F {

	static void solve() throws Exception {
		int n = scanInt();
		long l[] = new long[n];
		for (int i = 0; i < n; i++) {
			l[i] = scanLong();
		}
		long e1 = 0, e2 = 0, ans = 0;
		boolean water = false;
		String types = scanString();
		for (int i = 0; i < n; i++) {
			long li = l[i], cur;
			switch (types.charAt(i)) {
			case 'G':
				cur = min(e1, li);
				e1 -= cur;
				li -= cur;
				e2 += 2 * cur;
				ans += 2 * cur;
				e2 += li;
				ans += 3 * li;
				break;
			case 'W':
				water = true;
				e1 += li;
				ans += 2 * li;
				break;
			case 'L':
				cur = min(e1, li);
				e1 -= cur;
				li -= cur;
				ans += 2 * cur;
				cur = min(e2, li);
				e2 -= cur;
				li -= cur;
				ans += 3 * cur;
				ans += (water ? 4 : 6) * li;
				break;
			default:
				throw new AssertionError();
			}
		}
		out.print(ans);
	}

	static int scanInt() throws IOException {
		return parseInt(scanString());
	}

	static long scanLong() throws IOException {
		return parseLong(scanString());
	}

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

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	public static void main(String[] args) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			exit(1);
		}
	}
}

1091_F. New Year and the Mallard Expedition


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

public class Test3 {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int x=Integer.parseInt(br.readLine());
		int y=Integer.parseInt(br.readLine());
		System.out.print((int)(y%(Math.pow(2, x))));
	}
}


import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        StringTokenizer st;
        for(int z=0;z<t;z++){
            st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            st = new StringTokenizer(br.readLine());
            int min=1;
            int max=1;
            for(int i=0;i<n;i++){
                int k = Integer.parseInt(st.nextToken());
                if(max<k){
                    min = max;
                    max = k;
                }else if(min<k){
                    min = k;
                }
            }
            int res = Math.min(n-2,min-1);
            System.out.println(res);
        }
    }
}


// discussed with rainboy
import java.io.*;
import java.util.*;

public class CF915D {
	static ArrayList[] aa;
	static boolean[] visited, instack;
	static int[] stack;
	static int cnt, h_, i_, j_;
	static boolean dfs1(int i) {
		if (visited[i]) {
			if (instack[i]) {
				h_ = i;
				return true;
			}
			return false;
		}
		visited[i] = instack[i] = true;
		stack[cnt++] = i;
		ArrayList<Integer> adj = aa[i];
		for (int j : adj)
			if (dfs1(j))
				return true;
		instack[i] = false;
		cnt--;
		return false;
	}
	static boolean dfs2(int i) {
		if (visited[i])
			return instack[i];
		visited[i] = instack[i] = true;
		ArrayList<Integer> adj = aa[i];
		for (int j : adj)
			if (!(i == i_ && j == j_) && dfs2(j))
				return true;
		instack[i] = false;
		return false;
	}
	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());
		int m = Integer.parseInt(st.nextToken());
		aa = new ArrayList[n];
		for (int i = 0; i < n; i++)
			aa[i] = new ArrayList<Integer>();
		while (m-- > 0) {
			st = new StringTokenizer(br.readLine());
			int i = Integer.parseInt(st.nextToken()) - 1;
			int j = Integer.parseInt(st.nextToken()) - 1;
			aa[i].add(j);
		}
		visited = new boolean[n];
		instack = new boolean[n];
		stack = new int[n];
		for (int i = 0; i < n; i++)
			if (dfs1(i))
				break;
		if (cnt == 0) {
			System.out.println("YES");
			return;
		}
		for (j_ = h_, i_ = stack[--cnt]; ; j_ = i_, i_ = stack[--cnt]) {
			Arrays.fill(visited, false);
			Arrays.fill(instack, false);
			boolean cycle = false;
			for (int i = 0; i < n; i++)
				if (dfs2(i)) {
					cycle = true;
					break;
				}
			if (!cycle) {
				System.out.println("YES");
				return;
			}
			if (i_ == h_)
				break;
		}
		System.out.println("NO");
	}
}


//package fourninetysixDiv3;
import java.util.HashMap;
import java.util.Scanner;
public class Median_Segments_general {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		int m = s.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = s.nextInt();
		}
		System.out.println(func(n, m, arr)-func(n, m+1, arr));
	}
	public static long func(int n,int m,int[] arr) {
		HashMap<Long, Integer> map = new HashMap<>();
		map.put((long) 0, 1);
		long sum = 0;
		long res = 0;
		long add=0;
		for(int i=0;i<n;i++) {
			if(arr[i]<m) {
				sum--;
				if(map.containsKey(sum)) {
					add-=map.get(sum);
				}
			}
			else {
				if(map.containsKey(sum)) {
					add+=map.get(sum);
				}
				sum++;
			}
			res+=add;
			if(map.containsKey(sum)) {
				map.put(sum, map.get(sum)+1);
			}
			else {
				map.put(sum,1);
			}
		}
		return res;
	}
}

1005_E1. Median on Segments (Permutations Edition)


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

public class Main {

    private static void solve(InputReader in, OutputWriter out) {
        int n = in.nextInt();

        List<List<Integer>> g = new ArrayList<>(n + 1);
        for (int i = 0; i < n + 1; i++) {
            g.add(new LinkedList<>());
        }

        int degree1 = 0, degree2 = 0, root = 0;
        for (int i = 0; i < n - 1; i++) {
            int a = in.nextInt();
            int b = in.nextInt();

            g.get(a).add(b);
            g.get(b).add(a);

            if (g.get(a).size() > degree1) {

                if (a == root) {
                    degree1 = g.get(a).size();
                } else {
                    degree2 = degree1;
                    degree1 = g.get(a).size();
                    root = a;
                }

            } else if (g.get(a).size() > degree2) {
                degree2 = g.get(a).size();
            }

            if (g.get(b).size() > degree1) {

                if (b == root) {
                    degree1 = g.get(b).size();
                } else {
                    degree2 = degree1;
                    degree1 = g.get(b).size();
                    root = b;
                }

            } else if (g.get(b).size() > degree2) {
                degree2 = g.get(b).size();
            }
        }

        if (degree2 > 2) {
            out.print("No");
        } else {
            out.println("Yes");

            List<Integer> leaves = new LinkedList<>();
            for (int i = 1; i <= n; i++) {
                if (i != root) {
                    if (g.get(i).size() == 1) {
                        leaves.add(i);
                    }
                }
            }

            out.println(leaves.size());
            for (int i : leaves) {
                out.println(root + " " + i);
            }
        }
    }

    private static void shuffleArray(int[] array) {
        int index;
        Random random = new Random();
        for (int i = array.length - 1; i > 0; i--) {
            index = random.nextInt(i + 1);
            if (index != i) {
                array[index] ^= array[i];
                array[i] ^= array[index];
                array[index] ^= array[i];
            }
        }
    }

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        solve(in, out);
        in.close();
        out.close();
    }

    private static class InputReader {
        private BufferedReader br;
        private StringTokenizer st;

        InputReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
            st = null;
        }

        String nextLine() {
            String line = null;
            try {
                line = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return line;
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                String line = nextLine();
                if (line == null) return null;
                st = new StringTokenizer(line);
            }
            return st.nextToken();
        }

        byte nextByte() {
            return Byte.parseByte(next());
        }

        short nextShort() {
            return Short.parseShort(next());
        }

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

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

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

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static class OutputWriter {
        BufferedWriter bw;

        OutputWriter(OutputStream os) {
            bw = new BufferedWriter(new OutputStreamWriter(os));
        }

        void print(int i) {
            print(Integer.toString(i));
        }

        void println(int i) {
            println(Integer.toString(i));
        }

        void print(long l) {
            print(Long.toString(l));
        }

        void println(long l) {
            println(Long.toString(l));
        }

        void print(double d) {
            print(Double.toString(d));
        }

        void println(double d) {
            println(Double.toString(d));
        }

        void print(boolean b) {
            print(Boolean.toString(b));
        }

        void println(boolean b) {
            println(Boolean.toString(b));
        }

        void print(char c) {
            try {
                bw.write(c);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void println(char c) {
            println(Character.toString(c));
        }

        void print(String s) {
            try {
                bw.write(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void println(String s) {
            print(s);
            print('\n');
        }

        void close() {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


// practice with rainboy
import java.io.*;
import java.util.*;

public class CF903F {
	static final int INF = 0x3f3f3f3f;
	static void fill(int[][][][] aa, int a) {
		for (int h0 = 0; h0 <= 4; h0++)
			for (int h1 = 0; h1 <= 4; h1++)
				for (int h2 = 0; h2 <= 4; h2++)
					for (int h3 = 0; h3 <= 4; h3++)
						aa[h0][h1][h2][h3] = a;
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		StringTokenizer st = new StringTokenizer(br.readLine());
		int a1 = Integer.parseInt(st.nextToken());
		int a2 = Integer.parseInt(st.nextToken());
		int a3 = Integer.parseInt(st.nextToken());
		int a4 = Integer.parseInt(st.nextToken());
		int[] aa = new int[10];
		aa[0] = aa[1] = aa[2] = aa[3] = a1;
		aa[4] = aa[5] = aa[6] = a2;
		aa[7] = aa[8] = a3;
		aa[9] = a4;
		int[][] ww = new int[10][4];
		ww[0][0] = 1;
		ww[1][1] = 1;
		ww[2][2] = 1;
		ww[3][3] = 1;
		ww[4][0] = ww[4][1] = 2;
		ww[5][1] = ww[5][2] = 2;
		ww[6][2] = ww[6][3] = 2;
		ww[7][0] = ww[7][1] = ww[7][2] = 3;
		ww[8][1] = ww[8][2] = ww[8][3] = 3;
		ww[9][0] = ww[9][1] = ww[9][2] = ww[9][3] = 4;
		char[][] cc = new char[4][n + 8];
		for (int k = 0; k < 4; k++) {
			char[] c_ = cc[k];
			br.readLine().getChars(0, n, c_, 4);
			c_[0] = c_[1] = c_[2] = c_[3]
				= c_[n + 4] = c_[n + 5] = c_[n + 6] = c_[n + 7] = '.';
		}
		int[][][][] dp = new int[5][5][5][5];
		int[][][][] dq = new int[5][5][5][5];
		fill(dp, INF);
		dp[4][4][4][4] = 0;
		int[] hh = new int[4];
		for (int i = 0; i < n + 4; i++) {
			for (int h0 = 0; h0 <= 4; h0++)
				for (int h1 = 0; h1 <= 4; h1++)
					for (int h2 = 0; h2 <= 4; h2++)
						for (int h3 = 0; h3 <= 4; h3++)
							for (int s = 0; s < 10; s++) {
								hh[0] = h0;
								hh[1] = h1;
								hh[2] = h2;
								hh[3] = h3;
								for (int k = 0; k < 4; k++) {
									int h = ww[s][k];
									if (hh[k] < h) {
										while (h < 4 && cc[k][i + h] == '.')
											h++;
										hh[k] = h;
									}
								}
								int x = dp[h0][h1][h2][h3] + aa[s];
								if (dp[hh[0]][hh[1]][hh[2]][hh[3]] > x)
									dp[hh[0]][hh[1]][hh[2]][hh[3]] = x;
							}
			fill(dq, INF);
			for (int h0 = 1; h0 <= 4; h0++) {
				hh[0] = h0 < 4 || cc[0][i + 4] == '*' ? h0 - 1 : 4;
				for (int h1 = 1; h1 <= 4; h1++) {
					hh[1] = h1 < 4 || cc[1][i + 4] == '*' ? h1 - 1 : 4;
					for (int h2 = 1; h2 <= 4; h2++) {
						hh[2] = h2 < 4 || cc[2][i + 4] == '*' ? h2 - 1 : 4;
						for (int h3 = 1; h3 <= 4; h3++) {
							hh[3] = h3 < 4 || cc[3][i + 4] == '*' ? h3 - 1 : 4;
							int x = dp[h0][h1][h2][h3];
							if (dq[hh[0]][hh[1]][hh[2]][hh[3]] > x)
								dq[hh[0]][hh[1]][hh[2]][hh[3]] = x;
						}
					}
				}
			}
			int[][][][] tmp = dp; dp = dq; dq = tmp;
		}
		System.out.println(dp[4][4][4][4]);
	}
}


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

public class SFly {

	public static void main(String[] args) throws IOException {

		BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
		int planet = Integer.parseInt(lector.readLine());
		int ini = Integer.parseInt(lector.readLine());
		double peso = ini;
		int[] desp = new int[planet];
		int[] ater = new int[planet];
		String[] temp = lector.readLine().split(" ");
		for(int i=0; i<planet; i++) {
			desp[i] = Integer.parseInt(temp[i]);
			if(desp[i] == 1) {
				System.out.println(-1);
				lector.close();
				return;
			}
		}
		temp = lector.readLine().split(" ");
		for(int i=0; i<planet; i++) {
			ater[i] = Integer.parseInt(temp[i]);
			if(ater[i] == 1) {
				System.out.println(-1);
				lector.close();
				return;
			}
		}
		temp = null;
		int i=planet-1;
		peso = (peso*ater[0])/(ater[0]-1);
		while(i>0) {
			peso = (peso*desp[i])/(desp[i]-1);
			peso = (peso*ater[i])/(ater[i]-1);
			i--;
		}
		peso = (peso*desp[0])/(desp[0]-1);
		peso = peso - ini;
		System.out.println(peso);
		lector.close();
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

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

    static class TaskG {
        static int[][] g;
        static int n;
        static int[] a;
        static int[][] edges;
        static long[] dp;
        static long[] dpPathToRootWithDetours;
        static int time = 0;
        static int[] appearance;
        static int[] firstAppearance;
        static int[] depth;

        public static void dfs(int i, int parE) {
            firstAppearance[i] = time;
            appearance[time++] = i;
            dp[i] = a[i];
            for (int eIndex : g[i]) {
                if (eIndex == parE) continue;
                int child = i ^ edges[eIndex][0] ^ edges[eIndex][1];
                dfs(child, eIndex);
                appearance[time++] = i;
                dp[i] += Math.max(dp[child] - edges[eIndex][2] * 2, 0);
            }
        }

        public static void dfs2(int i, int parE) {
            if (i == 0) {
                dpPathToRootWithDetours[i] = dp[i];
            } else {
                int par = i ^ edges[parE][0] ^ edges[parE][1];
                depth[i] = depth[par] + 1;
                dpPathToRootWithDetours[i] = dpPathToRootWithDetours[par] - Math.max(0, dp[i] - edges[parE][2] * 2);
                dpPathToRootWithDetours[i] -= edges[parE][2];
                dpPathToRootWithDetours[i] += dp[i];

                long myPathWeight = Math.max(dp[i] - edges[parE][2] * 2, 0);
                long change = dp[par] - myPathWeight - edges[parE][2] * 2;
                change = Math.max(change, 0);
                dp[i] += change;
            }
            for (int eIndex : g[i]) {
                if (eIndex == parE) continue;
                dfs2(i ^ edges[eIndex][0] ^ edges[eIndex][1], eIndex);
            }
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.NextInt();
            int q = in.NextInt();
            a = in.NextIntArray(n);
            edges = new int[n - 1][3];
            {
                long[] count = new long[n];
                for (int i = 0; i < n - 1; i++) {
                    int u = in.NextInt() - 1;
                    int v = in.NextInt() - 1;
                    int w = in.NextInt();
                    edges[i][0] = u;
                    edges[i][1] = v;
                    edges[i][2] = w;
                    count[u]++;
                    count[v]++;
                }

                g = new int[n][];
                for (int i = 0; i < n; i++) {
                    g[i] = new int[(int) count[i]];
                }
                for (int i = 0; i < n - 1; i++) {
                    for (int j = 0; j < 2; j++) {
                        g[edges[i][j]][(int) --count[edges[i][j]]] = i;
                    }
                }
            }
            dp = new long[n];
            dpPathToRootWithDetours = new long[n];
            depth = new int[n];
            firstAppearance = new int[n];
            appearance = new int[(n - 1) * 2 + 1];
            dfs(0, -1);
            dfs2(0, -1);
            GraphLowestCommonAncestor.LCA lca = GraphLowestCommonAncestor.createLCA(appearance, firstAppearance, depth);
            firstAppearance = null;
            depth = null;
            appearance = null;
            edges = null;
            g = null;
            for (int i = 0; i < q; i++) {
                int u = in.NextInt() - 1;
                int v = in.NextInt() - 1;
                int lcaI = lca.getLCA(u, v);
                long res = dpPathToRootWithDetours[u] + dpPathToRootWithDetours[v] - 2 * dpPathToRootWithDetours[lcaI] + dp[lcaI];
                out.println(res);
            }
        }

    }

    static class MinRangeSparseTable implements ISearchInRange {
        private final int[][] sparseTables;
        private final long[] array;
        private final boolean reverseOrdered;

        public MinRangeSparseTable(long[] array, boolean reverseOrdered) {
            this.reverseOrdered = reverseOrdered;
            this.array = array;
            int LCALength = IntegerExtension.getNumberOfBits(array.length);
            sparseTables = new int[LCALength][];
            sparseTables[0] = new int[array.length];
            for (int i = 0; i < array.length; i++) {
                sparseTables[0][i] = i;
            }
            for (int i = 1; i < LCALength; i++) {
                int size = 1 << i;
                int jumpSize = 1 << (i - 1);
                sparseTables[i] = new int[sparseTables[0].length - size + 1];
                for (int j = 0; j < sparseTables[i].length; j++) {
                    sparseTables[i][j] = min(sparseTables[i - 1][j], sparseTables[i - 1][j + jumpSize]);
                }
            }
        }

        private int min(int a, int b) {
            return ((array[a] < array[b]) ^ reverseOrdered) ? a : b;
        }

        public Pair<Long, Long> queryIndexValueInRange(long l, long r) {
            int size = (int) (r - l + 1);
            int LCAIndex = IntegerExtension.getNumberOfBits(size) - 1;
            int sizeNeeded = 1 << LCAIndex;
            int res = min(sparseTables[LCAIndex][(int) l], sparseTables[LCAIndex][(int) (r - sizeNeeded + 1)]);
            return new Pair<>((long) res, array[res]);
        }

        public MinRangeSparseTable(long[] array) {
            this(array, false);
        }

    }

    static class GraphLowestCommonAncestor {
        public static GraphLowestCommonAncestor.LCA createLCA(int[] appearances, final int[] firstAppearance, final int[] depth) {
            return new GraphLowestCommonAncestor.LCA_MinRangeSparseTable(appearances, firstAppearance, depth);
        }

        public interface LCA {
            int getLCA(int a, int b);

        }

        private static class LCA_MinRangeSparseTable implements GraphLowestCommonAncestor.LCA {
            private final MinRangeSparseTable minRangeSparseTable;
            private final int[] firstAppearance;
            private final int[] indexToNode;

            public LCA_MinRangeSparseTable(int[] appearances, final int[] firstAppearance, final int[] depth) {
                this.firstAppearance = firstAppearance;
                this.indexToNode = appearances;
                long[] depthOrder = new long[appearances.length];
                for (int i = 0; i < depthOrder.length; i++) {
                    depthOrder[i] = depth[appearances[i]];
                }
                minRangeSparseTable = new MinRangeSparseTable(depthOrder);
            }

            public int getLCA(int a, int b) {
                a = firstAppearance[a];
                b = firstAppearance[b];
                int l = Math.min(a, b), r = Math.max(a, b);
                return indexToNode[(int) (long) minRangeSparseTable.queryIndexValueInRange(l, r).first];
            }

        }

    }

    static class InputReader {
        BufferedReader reader;
        StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

        public int[] NextIntArray(int n) {
            return NextIntArray(n, 0);
        }

        public int[] NextIntArray(int n, int offset) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = NextInt() + offset;
            }
            return a;
        }

    }

    static interface ISearchInRange {
    }

    static class Pair<T1, T2> {
        public T1 first;
        public T2 second;

        public Pair(T1 f, T2 s) {
            first = f;
            second = s;
        }

    }

    static class IntegerExtension {
        public static int getNumberOfBits(long i) {
            return 64 - Long.numberOfLeadingZeros(i);
        }

    }
}


import java.io.*;
import java.lang.*;
import java.util.*;
public class alex
{
    public static void main(String[] args)throws IOException
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();int sum=1;
        for(int i=1;i<=n;i++)
        {
            sum=sum+(4*(i-1));
        }
        System.out.println(sum);
    }
}


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

public class TaskB implements Runnable {
    boolean prime[] = new boolean[(int)1e6+10];
    InputReader c;
    PrintWriter w;

    public void run() {
        c = new InputReader(System.in);
        w = new PrintWriter(System.out);

        char a[] = c.next().toCharArray(), b[] = c.next().toCharArray();
        int n = a.length, m = b.length;

        int[][] prefix = new int[m][2];
        for(int i=0;i<m;i++){
            if(i!=0) {
                prefix[i][0] = prefix[i-1][0];
                prefix[i][1] = prefix[i-1][1];
            }
            prefix[i][b[i] - '0']++;
            //w.println(prefix[i][0]+" "+prefix[i][1]);
        }

        long res = 0;
        for(int i=0;i<n;i++){
            int temp = a[i] - '0';

            res += prefix[m - n + i][temp^1];
            if(i!=0) res -= prefix[i-1][temp^1];
        }

        w.println(res);

        w.close();
    }

    void sieveOfEratosthenes(int n) {
        for(int i=0;i<n;i++)
            prime[i] = true;

        for(int p = 2; p*p <=n; p++)
        {
            if(prime[p] == true)
            {
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }
    }
    class pair implements Comparable<pair>{
        char ch;
        int ind;

        @Override
        public String toString() {
            return "pair{" +
                    "ch=" + ch +
                    ", ind=" + ind +
                    '}';
        }

        public pair(char ch, int ind) {
            this.ch = ch;
            this.ind = ind;
        }
        public int compareTo(pair car) {
            if(this.ch==car.ch)
                return this.ind - car.ind;
            return this.ch - car.ch;
        }
    }
    public static void sortbyColumn(int arr[][], int col){
        Arrays.sort(arr, new Comparator<int[]>()
        {
            public int compare(int[] o1, int[] o2){
                return(Integer.valueOf(o1[col]).compareTo(o2[col]));
            }
        });

    }
    static long gcd(long a, long b){
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    public static class DJSet {
        public int[] upper;
        public DJSet(int n) {
            upper = new int[n];
            Arrays.fill(upper, -1);
        }

        public int root(int x) {
            return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
        }

        public boolean equiv(int x, int y) {
            return root(x) == root(y);
        }

        public boolean union(int x, int y) {
            x = root(x);
            y = root(y);
            if (x != y) {
                if (upper[y] < upper[x]) {
                    int d = x;
                    x = y;
                    y = d;
                }
                upper[x] += upper[y];
                upper[y] = x;
            }
            return x == y;
        }
    }
    public static int[] radixSort(int[] f) {
        int[] to = new int[f.length];
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;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 < f.length;i++)b[1+(f[i]>>>16)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        return f;
    }
    public void printArray(int[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    public int[] scanArrayI(int n){
        int a[] = new int[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextInt();
        return a;
    }
    public long[] scanArrayL(int n){
        long a[] = new long[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextLong();
        return a;
    }
    public void printArray(long[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        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 String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public 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;
        }

        public 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;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            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 boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new TaskB(),"TaskB",1<<26).start();
    }
}