F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

/*

    Author: Anthony Ngene

    Created: 05/10/2020 - 14:12

*/

import java.io.*;

import java.util.*;

public class F {

// checks: 1. edge cases   2. overflow   3. possible errors (e.g 1/0, arr[out])   4. time/space complexity

    void solver() throws IOException {

        int n = in.intNext();

        int[] arr = in.nextIntArray(n);

        HashMap<Integer, Deque<Tuple>> subSum = new HashMap<>();

        Integer best = null;

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

            int total = 0;

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

                total += arr[j];

                if (!subSum.containsKey(total)) subSum.put(total, new ArrayDeque<>());

                Deque<Tuple> rs = subSum.get(total);

                if (rs.size() > 0 && rs.peekLast().b > j) rs.pollLast();

                if (rs.size() == 0 || rs.peekLast().b < i)

                    rs.add(new Tuple(i, j));

                if (best == null || rs.size() > subSum.get(best).size())

                    best = total;

            }

        }

        Deque<Tuple> bestList = subSum.get(best);

        out.println(bestList.size());

        for (Tuple aa: bestList)

            out.pp(aa.a + 1, aa.b + 1);

    }

// Generated Code Below:

private static final FastWriter out = new FastWriter();

private static FastScanner in;

static ArrayList<Integer>[] adj;

private static long e97 = (long)1e9 + 7;

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

    in = new FastScanner();

    new F().solver();

    out.close();

}

static class FastWriter {

    private static final int IO_BUFFERS = 128 * 1024;

    private final StringBuilder out;

    public FastWriter() { out = new StringBuilder(IO_BUFFERS); }

    public FastWriter p(Object object) { out.append(object); return this; }

    public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }

    public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }

    public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(long[][] arr) {  for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(int[][] arr) {  for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(char[][] arr) {  for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(double[][] arr) {  for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public <T>void println(T[][] arr) {  for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public FastWriter println(Object object) { out.append(object).append("\n"); return this; }

    public void toFile(String fileName) throws IOException {

        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));

        writer.write(out.toString());

        writer.close();

    }

    public void close() throws IOException { System.out.print(out); }

}

static class FastScanner {

    private InputStream sin = System.in;

    private final byte[] buffer = new byte[1024];

    private int ptr = 0;

    private int buflen = 0;

    public FastScanner(){}

    public FastScanner(String filename) throws FileNotFoundException {

        File file = new File(filename);

        sin = new FileInputStream(file);

    }

    private boolean hasNextByte() {

        if (ptr < buflen) {

            return true;

        }else{

            ptr = 0;

            try {

                buflen = sin.read(buffer);

            } catch (IOException e) {

                e.printStackTrace();

            }

            if (buflen <= 0) {

                return false;

            }

        }

        return true;

    }

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

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

    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}

    public String next() {

        if (!hasNext()) throw new NoSuchElementException();

        StringBuilder sb = new StringBuilder();

        int b = readByte();

        while(isPrintableChar(b)) {

            sb.appendCodePoint(b);

            b = readByte();

        }

        return sb.toString();

    }

    public long longNext() {

        if (!hasNext()) throw new NoSuchElementException();

        long n = 0;

        boolean minus = false;

        int b = readByte();

        if (b == '-') {

            minus = true;

            b = readByte();

        }

        if (b < '0' || '9' < b) {

            throw new NumberFormatException();

        }

        while(true){

            if ('0' <= b && b <= '9') {

                n *= 10;

                n += b - '0';

            }else if(b == -1 || !isPrintableChar(b) || b == ':'){

                return minus ? -n : n;

            }else{

                throw new NumberFormatException();

            }

            b = readByte();

        }

    }

    public int intNext() {

        long nl = longNext();

        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();

        return (int) nl;

    }

    public double doubleNext() { return Double.parseDouble(next());}

    public long[] nextLongArray(final int n){

        final long[] a = new long[n];

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

            a[i] = longNext();

        return a;

    }

    public int[] nextIntArray(final int n){

        final int[] a = new int[n];

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

            a[i] = intNext();

        return a;

    }

    public double[] nextDoubleArray(final int n){

        final double[] a = new double[n];

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

            a[i] = doubleNext();

        return a;

    }

    public ArrayList<Integer>[] getAdj(int n) {

        ArrayList<Integer>[] adj = new ArrayList[n + 1];

        for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();

        return adj;

    }

    public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {

        return adjacencyList(nodes, edges, false);

    }

    public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {

        adj = getAdj(nodes);

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

            int a = intNext(), b = intNext();

            adj[a].add(b);

            if (!isDirected) adj[b].add(a);

        }

        return adj;

    }

}

static class u {

    public static int upperBound(long[] array, long obj) {

        int l = 0, r = array.length - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int upperBound(ArrayList<Long> array, long obj) {

        int l = 0, r = array.size() - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array.get(c)) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int lowerBound(long[] array, long obj) {

        int l = 0, r = array.length - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int lowerBound(ArrayList<Long> array, long obj) {

        int l = 0, r = array.size() - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array.get(c)) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }

    static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }

    static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }

    private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }

    private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }

    private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }

    private static void customSort(int[][] arr) {

        Arrays.sort(arr, new Comparator<int[]>() {

            public int compare(int[] a, int[] b) {

                if (a[0] == b[0]) return Integer.compare(a[1], b[1]);

                return Integer.compare(a[0], b[0]);

            }

        });

    }

    public static int[] swap(int[] arr, int left, int right) {

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

    public static char[] swap(char[] arr, int left, int right) {

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

    public static int[] reverse(int[] arr, int left, int right) {

        while (left < right) {

            int temp = arr[left];

            arr[left++] = arr[right];

            arr[right--] = temp;

        }

        return arr;

    }

    public static boolean findNextPermutation(int[] data) {

        if (data.length <= 1) return false;

        int last = data.length - 2;

        while (last >= 0) {

            if (data[last] < data[last + 1]) break;

            last--;

        }

        if (last < 0) return false;

        int nextGreater = data.length - 1;

        for (int i = data.length - 1; i > last; i--) {

            if (data[i] > data[last]) {

                nextGreater = i;

                break;

            }

        }

        data = swap(data, nextGreater, last);

        data = reverse(data, last + 1, data.length - 1);

        return true;

    }

    public static int biSearch(int[] dt, int target){

        int left=0, right=dt.length-1;

        int mid=-1;

        while(left<=right){

            mid = (right+left)/2;

            if(dt[mid] == target) return mid;

            if(dt[mid] < target) left=mid+1;

            else right=mid-1;

        }

        return -1;

    }

    public static int biSearchMax(long[] dt, long target){

        int left=-1, right=dt.length;

        int mid=-1;

        while((right-left)>1){

            mid = left + (right-left)/2;

            if(dt[mid] <= target) left=mid;

            else right=mid;

        }

        return left;

    }

    public static int biSearchMaxAL(ArrayList<Integer> dt, long target){

        int left=-1, right=dt.size();

        int mid=-1;

        while((right-left)>1){

            mid = left + (right-left)/2;

            if(dt.get(mid) <= target) left=mid;

            else right=mid;

        }

        return left;

    }

    private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(int[][] ob, int res){      for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(long[][] ob, long res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(char[][] ob, char res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }

    private static boolean same3(long a, long b, long c){

        if(a!=b) return false;

        if(b!=c) return false;

        if(c!=a) return false;

        return true;

    }

    private static boolean dif3(long a, long b, long c){

        if(a==b) return false;

        if(b==c) return false;

        if(c==a) return false;

        return true;

    }

    private static double hypotenuse(double a, double b){

        return Math.sqrt(a*a+b*b);

    }

    private static long factorial(int n) {

        long ans=1;

        for(long i=n; i>0; i--){ ans*=i; }

        return ans;

    }

    private static long facMod(int n, long mod) {

        long ans=1;

        for(long i=n; i>0; i--) ans = (ans * i) % mod;

        return ans;

    }

    private static long lcm(long m, long n){

        long ans = m/gcd(m,n);

        ans *= n;

        return ans;

    }

    private static long gcd(long m, long n) {

        if(m < n) return gcd(n, m);

        if(n == 0) return m;

        return gcd(n, m % n);

    }

    private static boolean isPrime(long a){

        if(a==1) return false;

        for(int i=2; i<=Math.sqrt(a); i++){  if(a%i == 0) return false;  }

        return true;

    }

    static long modInverse(long a, long mod) {

    /* Fermat's little theorem: a^(MOD-1) => 1

    Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */

        return binpowMod(a, mod - 2, mod);

    }

    static long binpowMod(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if (b % 2 == 1) res = (res * a) % mod;

            a = (a * a) % mod;

            b /= 2;

        }

        return res;

    }

    private static int getDigit2(long num){

        long cf = 1;    int d=0;

        while(num >= cf){   d++;    cf = 1<<d;  }

        return d;

    }

    private static int getDigit10(long num){

        long cf = 1;    int d=0;

        while(num >= cf){   d++;    cf*=10;     }

        return d;

    }

    private static boolean isInArea(int y, int x, int h, int w){

        if(y<0) return false;

        if(x<0) return false;

        if(y>=h) return false;

        if(x>=w) return false;

        return true;

    }

    private static ArrayList<Integer> generatePrimes(int n) {

        int[] lp = new int[n + 1];

        ArrayList<Integer> pr = new ArrayList<>();

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

            if (lp[i] == 0) {

                lp[i] = i;

                pr.add(i);

            }

            for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {

                lp[i * pr.get(j)] = pr.get(j);

            }

        }

        return pr;

    }

    static long nPrMod(int n, int r, long MOD) {

        long res = 1;

        for (int i = (n - r + 1); i <= n; i++) {

            res = (res * i) % MOD;

        }

        return res;

    }

    static long nCr(int n, int r) {

        if (r > (n - r))

            r = n - r;

        long ans = 1;

        for (int i = 1; i <= r; i++) {

            ans *= n;

            ans /= i;

            n--;

        }

        return ans;

    }

    static long nCrMod(int n, int r, long MOD) {

        long rFactorial = nPrMod(r, r, MOD);

        long first = nPrMod(n, r, MOD);

        long second = binpowMod(rFactorial, MOD-2, MOD);

        return  (first * second) % MOD;

    }

    static void printBitRepr(int n) {

        StringBuilder res = new StringBuilder();

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

            int mask = (1 << i);

            res.append((mask & n) == 0 ? "0" : "1");

        }

        out.println(res);

    }

    static String bitString(int n) {return Integer.toBinaryString(n);}

    static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed

    static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }

    static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }

    static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }

    static HashMap<Character, Integer> counts(String word) {

        HashMap<Character, Integer> counts = new HashMap<>();

        for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);

        return counts;

    }

    static HashMap<Integer, Integer> counts(int[] arr) {

        HashMap<Integer, Integer> counts = new HashMap<>();

        for (int value : arr) counts.merge(value, 1, Integer::sum);

        return counts;

    }

    static HashMap<Long, Integer> counts(long[] arr) {

        HashMap<Long, Integer> counts = new HashMap<>();

        for (long l : arr) counts.merge(l, 1, Integer::sum);

        return counts;

    }

    static HashMap<Character, Integer> counts(char[] arr) {

        HashMap<Character, Integer> counts = new HashMap<>();

        for (char c : arr) counts.merge(c, 1, Integer::sum);

        return counts;

    }

    static long hash(int x, int y) {

        return x* 1_000_000_000L +y;

    }

    static final Random random = new Random();

    static void sort(int[] a) {

        int n = a.length;// shuffle, then sort

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

            int oi = random.nextInt(n), temp = a[oi];

            a[oi] = a[i];

            a[i] = temp;

        }

        Arrays.sort(a);

    }

    static void sort(long[] arr) {

        shuffleArray(arr);

        Arrays.sort(arr);

    }

    static void shuffleArray(long[] arr) {

        int n = arr.length;

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

            long tmp = arr[i];

            int randomPos = i + random.nextInt(n-i);

            arr[i] = arr[randomPos];

            arr[randomPos] = tmp;

        }

    }

}

static class Tuple implements Comparable<Tuple> {

    int a;

    int b;

    int c;

    public Tuple(int a, int b) {

        this.a = a;

        this.b = b;

        this.c = 0;

    }

    public Tuple(int a, int b, int c) {

        this.a = a;

        this.b = b;

        this.c = c;

    }

    public int getA() { return a; }

    public int getB() { return b; }

    public int getC() { return c; }

    public int compareTo(Tuple other) {

        if (this.a == other.a) {

            if (this.b == other.b) return Long.compare(this.c, other.c);

            return Long.compare(this.b, other.b);

        }

        return Long.compare(this.a, other.a);

    }

    @Override

    public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }

    @Override

    public boolean equals(Object o) {

        if (!(o instanceof Tuple)) return false;

        Tuple pairo = (Tuple) o;

        return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);

    }

    @Override

    public String toString() { return String.format("(%d %d %d)  ", this.a, this.b, this.c); }

}

private static int abs(int a){  return (a>=0) ? a: -a;  }

private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }

private static long abs(long a){    return (a>=0) ? a: -a;  }

private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }

private static double abs(double a){    return (a>=0) ? a: -a;  }

private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }

}


A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands:  'L' (Left) sets the position x:=x−1x:=x−1;  'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.

import java.io.*;

import java.util.*;

/*

        Set<String> hash_Set = new HashSet<String>();

// Demonstrating Set using HashSet

        // Declaring object of type String

        Set<String> hash_Set = new HashSet<String>();

        // Adding elements to the Set

        // using add() method

        hash_Set.add("Geeks");

        hash_Set.add("For");

        hash_Set.add("Geeks");

        hash_Set.add("Example");

        hash_Set.add("Set");

        // Printing elements of HashSet object

        System.out.println(hash_Set);

 */

public class Main {

    static boolean flag = false;

    static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

    static PrintWriter out = new PrintWriter(System.out);

    static StringTokenizer tok;

    public static void check() throws IOException {

        if (tok == null || !tok.hasMoreTokens())

            tok = new StringTokenizer(read.readLine());

    }

    public static int nextInt() throws IOException {

        return Integer.parseInt(nextString());

    }

    public static long nextLong() throws IOException {

        return Long.parseLong(nextString());

    }

    public static double nextDouble() throws IOException {

        return Double.parseDouble(nextString());

    }

    public static String nextString() throws IOException {

        check();

        return tok.nextToken();

    }

    public static void println(Object o) {

        out.println(o);

        out.flush();

    }

    public static int[] nextArray(int n) throws IOException {

        int[] a = new int[n];

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

            a[i] = nextInt();

        return a;

    }

    static int findLCM(int x, int y) {

        //   LCM(a, b) = (a x b) / GCD(a, b)

        return (x * y) / findGCD(x, y);

    }

    static int findGCD(int x, int y) {

        int r = 0, a, b;

        a = (x > y) ? x : y;

        b = (x < y) ? x : y;

        r = b;

        while (a % b != 0) {

            r = a % b;

            a = b;

            b = r;

        }

        return r;

    }

    /*

    boolean [] primes = new boolean[n+1];

            for(int i =0; i<primes.length; i++){

                primes[i] =true;

            }

            for(int i =2; i*i< primes.length; i++){

                if(primes[i] == true){

                    for(int j = i*i; j<=n; j+=i){

                        primes[j] =false;

                    }

                }

            }

     */

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

        Scanner input = new Scanner(System.in);

        int t = input.nextInt();

        char[] x = input.next().toCharArray();

        int lCounter = 0;

        int rCounter = 0;

        for(int i = 0; i<x.length; i++){

            if(x[i] == 'L')

                lCounter++;

            else

                rCounter++;

        }

        out.write(lCounter+rCounter+1+"\n");

        out.flush();

        out.close();

    }

    }

/*

5

*

* *

* * *

* * * *

* * * * *

 */

/*

5

*

* *

* * *

* * * *

* * * * *

 */

/*

input:5

output:

*

**

***

****

*****

 */


D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

// package c1311;

//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// D. Three Integers
// https://codeforces.com/contest/1311/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given three integers a <= b <= c.
//
// In one move, you can add +1 or -1 to of these integers (i.e. increase or decrease any number by
// one). You can perform such operation any (possibly, zero) number of times, you can even perform
// this operation several times with one number. .
//
// You have to perform the minimum number of such operations in order to obtain three integers A <=
// B <= C such that B is divisible by A and C is divisible by B.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 100) -- the number of test cases.
//
// The next t lines describe test cases. Each test case is given on a separate line as three
// space-separated integers a, b and c (1 <= a <= b <= c <= 10^4).
//
// Output
//
// For each test case, print the answer. In the first line print res -- the minimum number of
// operations you have to perform to obtain three integers A <= B <= C such that B is divisible by A
// and C is divisible by B. On the second line print suitable triple A, B and C.
//
// Example
/*
input:
8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
output:
1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
*/
//

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

public class C1311D {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  static List<Integer>[] DIVS = computeDivisors(20000);

  static int[] solve(int a, int b, int c) {
    int[] ans = new int[4];
    // a,b,c in [1,10000]
    ans[0] = 50000;

    // Evaluate possible values of the middle number
    for (int v = 1; v <= 20000; v++) {
      int[] curr = new int[] {a, a, v, c};
      for (int x : DIVS[v]) {
        if (Math.abs(a - x) < curr[0]) {
          curr[0] = Math.abs(a - x);
          curr[1] = x;
        }
      }
      curr[0] += Math.abs(b - v);
      int r = c % v;
      if (c < v) {
        curr[0] += v - c;
        curr[3] = v;
      } else if (r != 0) {
        if (r <= v - r) {
          curr[0] += r;
          curr[3] = c - r;
        } else {
          curr[0] += v - r;
          curr[3] = c + (v - r);
        }
      }
      if (curr[0] < ans[0]) {
        ans = curr;
      }
    }
    return ans;
  }

  static List<Integer>[] computeDivisors(int n) {
    List<Integer>[] divs = new ArrayList[n + 1];
    for (int i = 0; i <= n; i++) {
      divs[i] = new ArrayList<>();
    }
    for (int i = 1; i <= n; i++) {
      for (int j = i; j <= n; j += i) {
        divs[j].add(i);
      }
    }
    return divs;
  }

  static void test(int[] exp, int a, int b, int c) {
    int[] ans = solve(a, b, c);
    boolean ok = exp[0] == ans[0] && exp[1] == ans[1] && exp[2] == ans[2] && exp[3] == ans[3];
    System.out.format("%d %d %d => %d %d %d %d %s\n",
        a, b, c, ans[0], ans[1], ans[2], ans[3],
        ok ? "":"Expected " + exp[0] + " " + exp[1] + " " + exp[2] + " " + exp[3]);
  }

  static boolean test = false;
  static void doTest() {
    if (!test) {
      return;
    }
    long t0 = System.currentTimeMillis();
    test(new int[] {2, 137, 10001, 10001}, 137, 10000, 10000);
    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    doTest();
    MyScanner in = new MyScanner();
    int T = in.nextInt();
    for (int t = 1; t <= T; t++) {
      int a = in.nextInt();
      int b = in.nextInt();
      int c = in.nextInt();
      int[] ans = solve(a, b, c);
      System.out.format("%d\n%d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
    }
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
      sb.append(v);
      sb.append(' ');
      if (sb.length() > 4000) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

    public MyScanner() {
      try {
        final String USERDIR = System.getProperty("user.dir");
        String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
        cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
        final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
        br = new BufferedReader(new InputStreamReader(fin.exists()
            ? new FileInputStream(fin) : System.in));
      } catch (Exception e) {
        br = new BufferedReader(new InputStreamReader(System.in));
      }
    }

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

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

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


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.lang.invoke.MethodHandles;

import java.util.*;

public class b {

	public static void main(String []args) {

		MyScanner s=new MyScanner();

	int n=s.nextInt();

		long a=s.nextLong();

		long b=s.nextLong();

		long k=s.nextLong();

		long []f=new long [n];

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

			f[i]=s.nextLong();

		long []t=new long [n];

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

			if(f[i]<=a)

			{

				t[i]=0;

			}

			else if(f[i]>a) {

				 long c=f[i]%(a+b);

				 if(c==0) {

					 long e=b/a;

					 if(b%a!=0)

						 e++;

					 t[i]=e;

				 }

				 else {

					 long d=c/a;

					 if(c%a!=0)

						 d++;

					 if(d>1)

					 t[i]=d-1;

					 else t[i]=0;

				 }

			 }

		}

		Arrays.sort(t);

		int res=0;

		for(long x:t) {

			if(k-x>=0) {

				res++;

				k=k-x;

			}

			// System.out.println(x);

		}

			 System.out.println(res);

	}

	public static  boolean is(String s) {

		int l=0;

		int r=s.length()-1;

		while(l<r) {

			if(s.charAt(l)!=s.charAt(r))

				return false;

			l++;r--;

		}

		return true;

	}

	public static void  shufu(int []f) {

		for(int i=0;i<f.length;i++) {

			int t=(int)Math.random()*f.length;

			int k=f[t];

			f[t]=f[i];

			f[i]=k;

		}

	}

	static class MyScanner {

	    BufferedReader br;

	    StringTokenizer st;

	    public MyScanner() {

	      try {

	        final String USERDIR = System.getProperty("user.dir");

	        String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");

	        cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;

	        final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");

	        br = new BufferedReader(new InputStreamReader(fin.exists()

	            ? new FileInputStream(fin) : System.in));

	      } catch (Exception e) {

	        br = new BufferedReader(new InputStreamReader(System.in));

	      }

	    }

	    public String next() {

	      try {

	        while (st == null || !st.hasMoreElements()) {

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

	        }

	        return st.nextToken();

	      } catch (Exception e) {

	        throw new RuntimeException(e);

	      }

	    }

	    public int nextInt() {

	      return Integer.parseInt(next());

	    }

	    public long nextLong() {

	      return Long.parseLong(next());

	    }

	  }

		}


C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    List<List<Integer>> g;

    int[][] parent;
    int[][] size;

    long[][] dp;

    int find_size(int v, int p) {
        if (size[p][v] != 0) {
            return size[p][v];
        }
        size[p][v] = 1;
        for (int u : g.get(v)) {
            if (u == p) continue;
            size[p][v] += find_size(u, v);
        }
        return size[p][v];
    }

    void find_parent(int root, int v, int p) {
        parent[v][root] = p;
        for (int u : g.get(v)) {
            if (u == p) continue;
            find_parent(root, u, v);
        }
    }

    void find_dp(int u, int v) {
        if (dp[u][v] != -1) return;
        find_dp(parent[u][v], v);
        find_dp(parent[v][u], u);
        dp[u][v] = size[parent[u][v]][u] * size[parent[v][u]][v] + Math.max(dp[parent[u][v]][v], dp[parent[v][u]][u]);
    }

    public void solve(InputReader in, PrintWriter out) {
        int n = in.nextInt();
        g = new ArrayList<>();
        for (int i = 0; i < n; ++i) {
            g.add(new ArrayList<>());
        }
        for (int i = 1; i < n; ++i) {
            int u = in.nextInt() - 1, v = in.nextInt() - 1;
            g.get(u).add(v);
            g.get(v).add(u);
        }

        parent = new int[n][n];
        for (int i = 0; i < n; ++i) {
            find_parent(i, i, -1);
        }

        size = new int[n][n];
        for (int i = 0; i < n; ++i) {
            for (int v : g.get(i)) {
                find_size(i, v);
            }
        }

        dp = new long[n][n];
        for (int i = 0; i < n; ++i) {
            Arrays.fill(dp[i], -1);
        }
        for (int i = 0; i < n; ++i) {
            dp[i][i] = 0;
        }
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (i == j) continue;
                find_dp(i, j);
            }
        }

        long answer = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                answer = Math.max(answer, dp[i][j]);
            }
        }
        out.println(answer);
    }

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

    static class InputReader {
        public BufferedReader reader;
        public 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());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

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


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

import java.util.*;

public class UnusualCompetitions {

	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);

		int n=sc.nextInt();

		String s=sc.next();

		char crr[]=s.toCharArray();

		int o=0,c=0,pos=-1,ans=0;

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

			if(crr[i]=='(') {

				o++;

			}

			else {

				c++;

			}

		}

		if(o!=c) {

			System.out.println(-1);

			return;

		}

		o=0;

		c=0;

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

//			System.out.println(o+" "+c);

			if(crr[i]=='(' && c>0) {

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

//					System.out.println(o+" "+c);

					if(crr[j]=='(') {

						o++;

					}

					else {

						c++;

					}

//					System.out.println(o+" "+c);

					if(o==c) {

//						System.out.println(o+" "+c);

//						System.out.println(pos+" "+j);

						ans+=(j-pos)+1;

						i=j;

						pos=-1;

						c=0;

						o=0;

						break;

					}

				}

			}

			else if(crr[i]=='(') {

				o++;

			}

			else if(crr[i]==')' && o>0){

				o--;

			}

			else {

				c++;

				if(pos==-1) {

					pos=i;

				}

			}

		}

		System.out.println(ans);

	}

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

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

        Reader input = new Reader();

        int n = input.nextInt();

        int[] a = new int[n];

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

            a[i] = input.nextInt();

        }

        int maxBit = getMaxBit(a);

        int mask = (1 << (maxBit-1));

        System.out.println(solve(a, mask));

    }

    static int solve(int[] a, int mask) {

        int answer = 0;

        while(mask > 0) {

            int zeros = 0;

            int ones = 0;

            for(int i = 0; i < a.length; ++i) {

                if((a[i]|mask) == a[i]) {

                    ++ones;

                } else {

                    ++zeros;

                }

            }

            if(zeros != 0 && ones != 0) {

                answer |= mask;

                int[] g1 = new int[ones];

                int[] g2 = new int[zeros];

                int onesPointer = 0, zerosPointer = 0;

                for(int i = 0; i < a.length; ++i) {

                    if((a[i]|mask) == a[i]) {

                        g1[onesPointer++] = a[i];

                    } else {

                        g2[zerosPointer++] = a[i];

                    }

                }

                int temp1 = solve(g1, mask>>1), temp2 = solve(g2, mask>>1);

                if(temp1 < temp2) {

                    answer = answer|temp1;

                } else {

                    answer = answer|temp2;

                }

                break;

            }

            mask = mask >> 1;

        }

        return answer;

    }

    static int getMaxBit(int[] a) {

        int max = a[0];

        for(int i = 1; i < a.length; ++i) {

            if(a[i] > max) max = a[i];

        }

        int bits = 0;

        while(max > 0) {

            ++bits;

            max = max>>1;

        }

        return bits;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

            while(string == null || ! string.hasMoreElements()) {

                string = new StringTokenizer(bufferedReader.readLine());

            }

            return string.nextToken();

        }

        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());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


import java.util.*;

public class Ap {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		int n = s.nextInt();

		String str = s.next();

		int sum=0;

		int pos=0;

		int co=0;

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

			if(str.charAt(i)=='(') {

				sum++;

			}

			else {

				sum--;

			}

			if(sum<0) {

				co++;

			}

			if(pos<0 && sum==0) {

				co++;

			}

			pos=sum;

		}

		if(sum!=0) System.out.println(-1);

		else {

			System.out.println(co);

		}

	}

}


B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is:  There are 44 subrectangles of size 22 consisting of only ones in it:  In second example matrix cc is:

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class cdf626b

{

	static long check(int arr[],long n)

	{

		long cou1=0,tot1=0;//,tot2=0,cou2=0;

		if(n>arr.length)

			return 0;

		for(int i=0;i<arr.length;i++)

		{

			if(arr[i]!=0)

				cou1++;

			if(cou1==n)

			{

				tot1++;

				cou1--;

			}

			if(arr[i]==0)

				cou1=0;

		}

		return tot1;

	}

	public static void main(String args[])throws Exception

	{

		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

		String s=br.readLine();

		String ss[]=s.split(" ");

		int n=Integer.parseInt(ss[0]);

		int m=Integer.parseInt(ss[1]);

		int k=Integer.parseInt(ss[2]);

		s=br.readLine();

		String str[]=s.split(" ");

		int arr[]=new int[n];

		long o1=0,o2=0;

		for(int j=0;j<n;j++)

		{

			arr[j]=Integer.parseInt(str[j]);

			if(arr[j]==1)

				o1++;

		}

		s=br.readLine();

		String ss1[]=s.split(" ");

		int arr1[]=new int[m];

		for(int j=0;j<m;j++)

		{

			arr1[j]=Integer.parseInt(ss1[j]);

			if(arr1[j]==1)

				o2++;

		}

		long copy=k,tempo=1;

		long ans=0;

		if(k==1)

		{

			ans=o1*o2;

			System.out.print(ans);

			return;

		}

		for(int i=1;i<=(int)Math.sqrt(k);i++)

		{

			if(k%i!=0)

			continue;

			if(i*i==k)

			{

				ans=ans+check(arr,i)*check(arr1,k/i);

				break;

			}

			ans=ans+check(arr,i)*check(arr1,k/i)+check(arr,k/i)*check(arr1,i);

		}

		System.out.println(ans);

	}

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

//some updates in import stuff

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

/*

    Always check before submitting list

    -> int to long conversion needed

    -> while loop mein break case shi ho

    -> extra kuch output na ho rha free fund mein

*/

//update this bad boi too

public class Main{

    static int mod = (int) (Math.pow(10, 9)+7);

	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };

	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };

	static final double eps = 1e-10;

	static Set<Integer> primeNumbers = new HashSet<>();

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

        MyScanner sc = new MyScanner();

        //changes in this line of code

        out = new PrintWriter(new BufferedOutputStream(System.out));

        // out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));

        //Write Code Below

        int n = sc.nextInt();

        long m = sc.nextInt();

        //now what??

        //n!

        long[] fact = new long[n+1];

        fact[0] = 1;

        for(long i = 1; i <= n; i++){

            fact[(int)i] = (i*fact[(int)(i-1)])%m;

        }

        long segments = 0;

        for(long i = 1; i <= n; i++){

            long first = (long)(n-i+1);

            long second = fact[(int)(n-i+1)];

            long third = fact[(int)i];

            long fourth = (first * second)% m;

            long fifth = (fourth* third)%m;

            segments = (segments + fifth)%m;

        }

        out.println(segments);

        out.close();

    }

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

 //Updation Required

    //Fenwick Tree (customisable)

    //Segment Tree (customisable)

    //-----CURRENTLY PRESENT-------//

    //Graph

    //DSU

    //powerMODe

    //power

    //Segment Tree (work on this one)

    //Prime Sieve

    //Count Divisors

    //Next Permutation

    //Get NCR

    //isVowel

    //Sort (int)

    //Sort (long)

    //Binomial Coefficient

    //Pair

    //Triplet

    //lcm (int & long)

    //gcd (int & long)

    //gcd (for binomial coefficient)

    //swap (int & char)

    //reverse

    //SOME LATEST UPDATIONS!!!

    //mod_mul

    //mod_div

    //Fast input and output

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //finding combinations in O(1) (basically the most basic logic you can think of)

    //not that complicated as i though it of

    //GRAPH (basic structure)

    public static class Graph{

        public int V;

        public ArrayList<ArrayList<Integer>> edges;

        //2 -> [0,1,2] (current)

        Graph(int V){

            this.V  = V;

            edges = new ArrayList<>(V+1);

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

                edges.add(new ArrayList<>());

            }

        }

        public void addEdge(int from , int to){

            edges.get(from).add(to);

        }

    }

    //DSU (path and rank optimised)

    public static class DisjointUnionSets {

        int[] rank, parent;

        int n;

        public DisjointUnionSets(int n)

        {

            rank = new int[n];

            parent = new int[n];

            Arrays.fill(rank, 1);

            Arrays.fill(parent,-1);

            this.n = n;

        }

        public int find(int curr){

            if(parent[curr] == -1)

                return curr;

            //path compression optimisation

            return parent[curr] = find(parent[curr]);

        }

        public void union(int a, int b){

            int s1 = find(a);

            int s2 = find(b);

            if(s1 != s2){

                if(rank[s1] < rank[s2]){

                    parent[s1] = s2;

                    rank[s2] += rank[s1];

                }else{

                    parent[s2] = s1;

                    rank[s1] += rank[s2];

                }

            }

        }

    }

    //with mod

    public static long powerMOD(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

            if ((y & 1) != 0){

                x %= mod;

                res %= mod;

                res = (res * x)%mod;

            }

            // y must be even now

            y = y >> 1; // y = y/2

            x%= mod;

            x = (x * x)%mod;  // Change x to x^2

        }

        return res%mod;

    }

    //without mod

    public static long power(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

            if ((y & 1) != 0){

                res = (res * x);

            }

            // y must be even now

            y = y >> 1; // y = y/

            x = (x * x);

        }

        return res;

    }

    public static class segmentTree{

        public long[] arr;

        public long[] tree;

        public long[] lazy;

        segmentTree(long[] array){

            int n = array.length;

            arr = new long[n];

            for(int i= 0; i < n; i++) arr[i] = array[i];

            tree = new long[4*n + 1];

            lazy = new long[4*n + 1];

        }

        public  void build(int[]arr, int s, int e, int[] tree, int index){

            if(s == e){

                tree[index] = arr[s];

                return;

            }

            //otherwise divide in two parts and fill both sides simply

            int mid = (s+e)/2;

            build(arr, s, mid, tree, 2*index);

            build(arr, mid+1, e, tree, 2*index+1);

            //who will build the current position dude

            tree[index] = Math.min(tree[2*index], tree[2*index+1]);

        }

        public  int query(int sr, int er, int sc, int ec, int index, int[] tree){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(sc != ec){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(sr > ec || sc > er) return Integer.MAX_VALUE;

            //found the index baby

            if(sr <= sc && ec <= er) return tree[index];

            //finding the index on both sides hehehehhe

            int mid = (sc + ec)/2;

            int left = query(sr, er, sc, mid, 2*index, tree);

            int right = query(sr, er, mid+1, ec, 2*index + 1, tree);

            return Integer.min(left, right);

        }

        //now we will do point update implementation

        //it should be simple then we expected for sure

        public  void update(int index, int indexr, int increment, int[] tree, int s, int e){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] = lazy[index];

                    lazy[2*index] = lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(indexr < s || indexr > e) return;

            //found the required index

            if(s == e){

                tree[index] += increment;

                return;

            }

            //search for the index on both sides

            int mid = (s+e)/2;

            update(2*index, indexr, increment, tree, s, mid);

            update(2*index+1, indexr, increment, tree, mid+1, e);

            //now update the current range simply

            tree[index] = Math.min(tree[2*index+1], tree[2*index]);

        }

        public  void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){

            //if not at all in the same range

            if(e < sr || er < s) return;

            //complete then also move forward

            if(s == e){

                tree[index] += increment;

                return;

            }

            //otherwise move in both subparts

            int mid = (s+e)/2;

            rangeUpdate(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);

            //update current range too na

            //i always forget this step for some reasons hehehe, idiot

            tree[index] = Math.min(tree[2*index], tree[2*index + 1]);

        }

        public  void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){

            //update lazy values

            //resolve lazy value before going down

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap case

            if(sr > e || s > er) return;

            //complete overlap

            if(sr <= s && er >= e){

                tree[index] += increment;

                if(s != e){

                    lazy[2*index+1] += increment;

                    lazy[2*index] += increment;

                }

                return;

            }

            //otherwise go on both left and right side and do your shit

            int mid = (s + e)/2;

            rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);

            tree[index] = Math.min(tree[2*index+1], tree[2*index]);

            return;

        }

    }

    //prime sieve

    public static void primeSieve(int n){

        BitSet bitset = new BitSet(n+1);

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

            if (i == 0 || i == 1) {

                bitset.set((int) i);

                continue;

            }

            if(bitset.get((int) i)) continue;

            primeNumbers.add((int)i);

            for(long j = i; j <= n ; j+= i)

                bitset.set((int)j);

        }

    }

    //number of divisors

    // public static int countDivisors(long number){

    //     if(number == 1) return 1;

    //     List<Integer> primeFactors = new ArrayList<>();

    //     int index = 0;

    //     long curr = primeNumbers.get(index);

    //     while(curr * curr <= number){

    //         while(number % curr == 0){

    //             number = number/curr;

    //             primeFactors.add((int) curr);

    //         }

    //         index++;

    //         curr = primeNumbers.get(index);

    //     }

    //     if(number != 1) primeFactors.add((int) number);

    //     int current = primeFactors.get(0);

    //     int totalDivisors = 1;

    //     int currentCount = 2;

    //     for (int i = 1; i < primeFactors.size(); i++) {

    //         if (primeFactors.get(i) == current) {

    //             currentCount++;

    //         } else {

    //             totalDivisors *= currentCount;

    //             currentCount = 2;

    //             current = primeFactors.get(i);

    //         }

    //     }

    //     totalDivisors *= currentCount;

    //     return totalDivisors;

    // }

    //now adding next permutation function to java hehe

    public static boolean next_permutation(int[] p) {

        for (int a = p.length - 2; a >= 0; --a)

          if (p[a] < p[a + 1])

            for (int b = p.length - 1;; --b)

              if (p[b] > p[a]) {

                int t = p[a];

                p[a] = p[b];

                p[b] = t;

                for (++a, b = p.length - 1; a < b; ++a, --b) {

                  t = p[a];

                  p[a] = p[b];

                  p[b] = t;

                }

                return true;

              }

        return false;

    }

    //is vowel function

    public static boolean isVowel(char c)

    {

        return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' ||     c=='u' || c=='U');

    }

    //to sort the array with better method

	public static void sort(int[] a) {

		ArrayList<Integer> l=new ArrayList<>();

		for (int i:a) l.add(i);

		Collections.sort(l);

		for (int i=0; i<a.length; i++) a[i]=l.get(i);

	}

    //sort long

    public static void sort(long[] a) {

		ArrayList<Long> l=new ArrayList<>();

		for (long i:a) l.add(i);

		Collections.sort(l);

		for (int i=0; i<a.length; i++) a[i]=l.get(i);

	}

    //for calculating binomialCoeff

    public static int binomialCoeff(int n, int k)

    {

        int C[] = new int[k + 1];

        // nC0 is 1

        C[0] = 1;

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

            // Compute next row of pascal

            // triangle using the previous row

            for (int j = Math.min(i, k); j > 0; j--)

                C[j] = C[j] + C[j - 1];

        }

        return C[k];

    }

    //Pair with int int

    public static class Pair{

        public int a;

        public int b;

        Pair(int a , int b){

            this.a = a;

            this.b = b;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Triplet with int int int

    public static class Triplet{

        public int a;

        public int b;

        public int c;

        Triplet(int a , int b, int c){

            this.a = a;

            this.b = b;

            this.c = c;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Shortcut function

    public static long lcm(long a , long b){

        return a * (b/gcd(a,b));

    }

    //let's make one for calculating lcm basically

    public static int lcm(int a , int b){

        return (a * b)/gcd(a,b);

    }

    //int version for gcd

    public static int gcd(int a, int b){

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

    //long version for gcd

    public static long gcd(long a, long b){

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

     //for ncr calculator(ignore this code)

     public static long __gcd(long n1, long n2)

     {

         long gcd = 1;

         for (int i = 1; i <= n1 && i <= n2; ++i) {

             // Checks if i is factor of both integers

             if (n1 % i == 0 && n2 % i == 0) {

                 gcd = i;

             }

         }

         return gcd;

     }

    //swapping two elements in an array

    public static void swap(int[] arr, int left , int right){

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //for char array

    public static void swap(char[] arr, int left , int right){

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //reversing an array

    public static void reverse(int[] arr){

        int left = 0;

        int right = arr.length-1;

        while(left <= right){

            swap(arr, left,right);

            left++;

            right--;

        }

    }

    public static long expo(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if ((b & 1) == 1L) res = (res * a) % mod;  //think about this one for a second

            a = (a * a) % mod;

            b = b >> 1;

        }

        return res;

    }

    //SOME EXTRA DOPE FUNCTIONS

    public static long mminvprime(long a, long b) {

        return expo(a, b - 2, b);

    }

    public static long mod_add(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a + b) % m) + m) % m;

    }

    public static long mod_sub(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a - b) % m) + m) % m;

    }

    public static long mod_mul(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a * b) % m) + m) % m;

    }

    public static long mod_div(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (mod_mul(a, mminvprime(b, m), m) + m) % m;

    }

    //O(n) every single time remember that

    public static long nCr(long N, long K , long mod){

        long upper = 1L;

        long lower = 1L;

        long lowerr = 1L;

        for(long i = 1; i <= N; i++){

            upper = mod_mul(upper, i, mod);

        }

        for(long i = 1; i <= K; i++){

            lower = mod_mul(lower, i, mod);

        }

        for(long i = 1; i <= (N - K); i++){

            lowerr = mod_mul(lowerr, i, mod);

        }

        // out.println(upper + " " + lower + " " + lowerr);

        long answer = mod_mul(lower, lowerr, mod);

        answer = mod_div(upper, answer, mod);

        return answer;

    }

    // ll *fact = new ll[2 * n + 1];

	// ll *ifact = new ll[2 * n + 1];

	// fact[0] = 1;

	// ifact[0] = 1;

	// for (ll i = 1; i <= 2 * n; i++)

	// {

	// 	fact[i] = mod_mul(fact[i - 1], i, MOD1);

	// 	ifact[i] = mminvprime(fact[i], MOD1);

	// }

    //ifact is basically inverse factorial in here!!!!!(imp)

    public static long combination(long n, long r, long m, long[] fact, long[] ifact) {

        long val1 = fact[(int)n];

        long val2 = ifact[(int)(n - r)];

        long val3 = ifact[(int)r];

        return (((val1 * val2) % m) * val3) % m;

    }

    //-----------PrintWriter for faster output---------------------------------

    public static PrintWriter out;

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

      BufferedReader br;

      StringTokenizer st;

        public MyScanner() {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        // public MyScanner() throws FileNotFoundException {

        //     br = new BufferedReader(new FileReader("input.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;

        }

    }

   //--------------------------------------------------------

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

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

public class App {
    public static void main (String[] args) throws java.lang.Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        //reader = new BufferedReader(new FileReader(new File("C:\\Users\\Anjali\\Desktop\\projects\\HelloWorld\\src\\input.txt")));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        //writer = new BufferedWriter(new FileWriter(new File("C:\\Users\\Anjali\\Desktop\\projects\\HelloWorld\\src\\output.txt")));
		//int tests = Integer.parseInt(reader.readLine());
        int tests = 1;
		//StringBuilder sb = new StringBuilder(tests);
		while (tests-- > 0){
		    solve(reader, writer);
            writer.write("\n");
		}
		reader.close();
        writer.flush();
        writer.close();
    }

    static void solve(BufferedReader reader, BufferedWriter writer) throws  IOException {
		int tests = Integer.parseInt(reader.readLine());
		for (int j = 0; j < tests; j++) {
			String[] input = reader.readLine().split(" ");
			int n = Integer.parseInt(input[0]);
			int d = Integer.parseInt(input[1]);
			int[] a = new int[n + 1];
			String[] input1 = reader.readLine().split(" ");
			for (int i = 0; i < n; i++) {
				a[i + 1] = Integer.parseInt(input1[i]);
			}
			for (int i = 0; i < d; i++) {
				for (int k = 2; k <= n; k++) {
					if (a[k] > 0) {
						a[k]--;
						a[k - 1]++;
						break;
					}
				}
			}
			writer.write(a[1]+ "\n");
		}
	}
}


D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

import java.io.*;

import java.util.*;

public class Main{

	static int[][][]dest;

	static int []dx= {0,1,0,-1},dy= {1,0,-1,0};

	static char []dir= {'L','U','R','D'};

	static char ans[][];

	static boolean valid(int x,int y) {

		return x>=0 && y>=0 && x<n && y<n;

	}

	static int n;

	static boolean yes=true;

	static void dfs(int x,int y,char direction) {

		if(ans[x][y]!='O')return;

		ans[x][y]=direction;

		for(int j=0;j<4;j++) {

			int xx=x+dx[j],yy=y+dy[j];

			if(!valid(xx, yy))continue;

			if(dest[xx][yy][0]==dest[x][y][0] && dest[xx][yy][1]==dest[x][y][1]) {

				dfs(xx, yy, dir[j]);

			}

		}

	}

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

		MScanner sc=new MScanner(System.in);

		PrintWriter pw=new PrintWriter(System.out);

		n=sc.nextInt();

		dest=new int[n][n][2];

		ans=new char[n][n];

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

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

				dest[i][j][0]=sc.nextInt()-1;dest[i][j][1]=sc.nextInt()-1;

				ans[i][j]='O';

			}

		}

		for(int x=0;x<n && yes;x++) {

			for(int y=0;y<n && yes;y++) {

				if(dest[x][y][0]==-2) {

					boolean ok=false;

					for(int j=0;j<4;j++) {

						int xx=x+dx[j],yy=y+dy[j];

						if(!valid(xx, yy))continue;

						if(dest[xx][yy][0]==-2 && dest[xx][yy][1]==-2) {

							ans[x][y]=dir[(j+2)%4];

							ok=true;

							break;

						}

					}

					if(!ok) {

						yes=false;

					}

				}

				else {

					if(dest[x][y][0]==x && dest[x][y][1]==y)

						dfs(x, y, 'X');

				}

			}

		}

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

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

				if(ans[i][j]=='O')yes=false;

			}

		}

		if(!yes) {

			pw.println("INVALID");

		}

		else {

			pw.println("VALID");

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

				for(int j=0;j<n;j++)pw.print(ans[i][j]);

				pw.println();

			}

		}

		pw.flush();

	}

	static class MScanner {

		StringTokenizer st;

		BufferedReader br;

		public MScanner(InputStream system) {

			br = new BufferedReader(new InputStreamReader(system));

		}

		public MScanner(String file) throws Exception {

			br = new BufferedReader(new FileReader(file));

		}

		public String next() throws IOException {

			while (st == null || !st.hasMoreTokens())

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

			return st.nextToken();

		}

		public int[] takearr(int n) throws IOException {

	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();

	        return in;

		}

		public long[] takearrl(int n) throws IOException {

	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public Integer[] takearrobj(int n) throws IOException {

	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();

	        return in;

		}

		public Long[] takearrlobj(int n) throws IOException {

	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public String nextLine() throws IOException {

			return br.readLine();

		}

		public int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		public double nextDouble() throws IOException {

			return Double.parseDouble(next());

		}

		public char nextChar() throws IOException {

			return next().charAt(0);

		}

		public Long nextLong() throws IOException {

			return Long.parseLong(next());

		}

		public boolean ready() throws IOException {

			return br.ready();

		}

		public void waitForInput() throws InterruptedException {

			Thread.sleep(3000);

		}

	}

}