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

		}

	}

}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

//package com.company;//Read minute details if coming wrong for no idea questions

import java.util.*;

import java.io.*;

public  class Main {

    public static class Suffix implements Comparable<Suffix>

    {

        int index;

        int rank;

        int next;

        public Suffix(int ind, int r, int nr)

        {

            index = ind;

            rank = r;

            next = nr;

        }

        public int compareTo(Suffix s)

        {

            if (rank != s.rank) return Integer.compare(rank, s.rank);

            return Integer.compare(next, s.next);

        }

    }

    public static int[] suffixArray(String s)

    {

        int n = s.length();

        Suffix[] su = new Suffix[n];

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

        {

            su[i] = new Suffix(i, s.charAt(i) - '$', 0);

        }

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

            su[i].next = (i + 1 < n ? su[i + 1].rank : -1);

        Arrays.sort(su);

        int[] ind = new int[n];

        for (int length = 4; length < 2 * n; length <<= 1)

        {

            int rank = 0, prev = su[0].rank;

            su[0].rank = rank;

            ind[su[0].index] = 0;

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

            {

                if (su[i].rank == prev &&

                        su[i].next == su[i - 1].next)

                {

                    prev = su[i].rank;

                    su[i].rank = rank;

                }

                else

                {

                    prev = su[i].rank;

                    su[i].rank = ++rank;

                }

                ind[su[i].index] = i;

            }

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

            {

                int nextP = su[i].index + length / 2;

                su[i].next = nextP < n ?

                        su[ind[nextP]].rank : -1;

            }

            Arrays.sort(su);

        }

        int[] suf = new int[n];

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

            suf[i] = su[i].index;

        return suf;

    }

    static class pair implements Comparable<pair> {

        long a = 0;

        long b = 0;

        // int cnt;

        pair(long b, long a) {

            this.a = b;

            this.b = a;

            // cnt = x;

        }

        @Override

        public int compareTo(pair o) {

            if(this.a != o.a)

                return (int) (this.a - o.a);

            else

                return (int) (this.b - o.b);

        }

        public boolean equals(Object o) {

            if (o instanceof pair) {

                pair p = (pair) o;

                return p.a == a && p.b == b;

            }

            return false;

        }

        public int hashCode() {

            return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());

        }

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

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

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

            this.bw = new BufferedWriter(new OutputStreamWriter(System.out));

        }

        public void prlong(Object object) throws IOException {

            bw.append("" + object);

        }

        public void prlongln(Object object) throws IOException {

            prlong(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

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

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS

//    HashSet<Long> set = new HashSet<>();

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

//        int b = 0;

//        long h = 1;

//        for(int j=i; j<s.length(); j++){

//            h = 131*h + (int)s.charAt(j);

//            b += bad[(int)(s.charAt(j)-'a')];

//            if(b<=k){

//                set.add(h);

//            }

//        }

//    }

//                System.out.println(set.size());

    //dsu

    static int[] par, rank;

    public static void dsu(int n) {

        par = new int[n];

        rank = new int[n];

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

            par[i] = i;

            rank[i] = 1;

        }

    }

    static int find(int u) {

        return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));

    }

    static void union(int u, int v) {

        int a = find(u), b = find(v);

        if (a != b && a != -1 && b != -1) {

            par[b] = a;

            rank[a] += rank[b];

        }

    }

    static void disunion(int u, int v) {

        int a = find(u), b = find(v);

        if (a != -1 && a == b) {

            par[a] = -1;

        }

    }

    static class Calc_nCr {

        private final long[] fact;

        private final long[] invfact;

        private final int p;

        Calc_nCr(int n, int prime) {

            fact = new long[n + 5];

            invfact = new long[n + 5];

            p = prime;

            fact[0] = 1;

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

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

            }

            invfact[n] = pow(fact[n], p - 2, p);

            for (int i = n - 1; i >= 0; i--) {

                invfact[i] = (invfact[i + 1] * (i + 1)) % p;

            }

        }

        private long nCr(int n, int r) {

            if (r > n || n < 0 || r < 0) return 0;

            return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;

        }

        private static long pow(long a, long b, int mod) {

            long result = 1;

            while (b > 0) {

                if ((b & 1L) == 1) {

                    result = (result * a) % mod;

                }

                a = (a * a) % mod;

                b >>= 1;

            }

            return result;

        }

    }

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

        }

    }

    public static void buildtreemin( long a[], long tr[],int st , int end , int node,int yo,int x  )

    {

        if(st==end)

        { tr[node]=a[st];

            return ;}

        int mid =(st+end)/2;

        buildtreemin(a,tr,st,mid,2*node,1+yo,x);

        buildtreemin(a,tr,mid+1,end,2*node+1,1+yo,x);

      tr[node] = Math.min(tr[2 * node] ,tr[2 * node + 1]);

    }

    public static void buildtreemax( long a[], long tr[],int st , int end , int node,int yo,int x  )

    {

        if(st==end)

        { tr[node]=a[st];

            return ;}

        int mid =(st+end)/2;

        buildtreemax(a,tr,st,mid,2*node,1+yo,x);

        buildtreemax(a,tr,mid+1,end,2*node+1,1+yo,x);

        tr[node] = Math.max(tr[2 * node] ,tr[2 * node + 1]);

    }

    public  static  long qtreemin(long tr[],int node ,  int l , int r , int beg ,int end )

    {

        if(l>end||r<beg)

            return Integer.MAX_VALUE;

        if(l<=beg&&end<=r)

            return tr[node];

        int mid =(beg+end)/2;

        long op1 =qtreemin(tr,2*node,l,r,beg,mid);

        long op2 =qtreemin(tr,2*node+1,l,r,mid+1,end);

        return Math.min(op1,op2);

    }

    public  static  long qtreemax(long tr[],int node ,  int l , int r , int beg ,int end )

    {

        if(l>end||r<beg)

            return Integer.MIN_VALUE;

        if(l<=beg&&end<=r)

            return tr[node];

        int mid =(beg+end)/2;

        long op1 =qtreemax(tr,2*node,l,r,beg,mid);

        long op2 =qtreemax(tr,2*node+1,l,r,mid+1,end);

        return Math.max(op1,op2);

    }

    public static int sumof(long a)

    {

        String s =a+"";

        int x =0;

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

            x=x+(s.charAt(i)-'0');

        return x;

    }

    public static void upd(long a[],long tr[], int node ,int beg , int end , int idx, long val,int yo,int x)

    {

        if(beg==end)

        {

            a[beg]=sumof(a[beg]);

            tr[node]=sumof(a[beg]);

            return ;

        }

        int mid =(beg+end)/2;

        if(idx>mid)

        {

            upd(a,tr,2*node+1,mid+1,end,idx,val,1+yo,x);

        }

        else

        {

            upd(a,tr,2*node,beg,mid,idx,val,1+yo,x);

        }

        { tr[node] = (tr[2 * node] + tr[2 * node + 1]);

        }

    }

    public static int  upper_bound(long arr[], int key)

    {

        int mid, N = arr.length;

        int low = 0;

        int high = N;

        while (low < high && low != N) {

            mid = low + (high - low) / 2;

            if (key > arr[mid]) {

                low = mid + 1;

            }

            else {

                high = mid;

            }

        }

        if (low == N ) {

            return -1;

        }

        return low ;

    }

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

//            int mx=1000000;

//            boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];

//            for (int i = 0; i <= mx; i++) {

//                isPrime[i] = true;

//            }

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

//                primeDiv[i]=i;

//            isPrime[0] = isPrime[1] = false;

//            for (long i = 2; i <= mx; i++) {

//                if (isPrime[(int)i]) {

//                    for (long j = i*i; j <= mx; j += i) {

//                        if (primeDiv[(int)j] == j) {

//                            primeDiv[(int)j] = (int)i;

//                        }

//                        isPrime[(int)j] = false;

//                    }

//                }

//            }

//

//            ArrayList<Integer>[] divisors = new ArrayList[(int) 1e5 + 5];

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

//                divisors[i] = new ArrayList<>();

//            }

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

//                for (int j = 1; j <= Math.sqrt(i); j++) {

//                    if (i % j == 0) {

//                        divisors[i].add(j);

//                        if (i / j != j)

//                            divisors[i].add(i / j);

//                    }

//                }

//            }

//            System.out.println(

//                    String.format("%.12f", x));

            int testCases=1;

            long mod =1000000007;

            // System.out.println(c);

            long fact[]=new long[300001];

            fact[0]=1;

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

            {

                fact[i]=fact[i-1]*(long) i;

                fact[i]=fact[i]%998244353;

            }

            fl:

            while (testCases-- > 0) {

int n =in.nextInt();

long a[]=new long[n];

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

    a[i]=in.nextLong();

long b[]=new long[n];

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

    b[i]=in.nextLong();

long dif[]=new long[n];

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

    dif[i]=a[i]-b[i];

long x[]=new long[n];

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

    x[i]=-dif[i];

sort(dif);

sort(x);

//for(long i :dif)

//    System.out.print(i+" ");

//                System.out.println();

//                for(long i :x)

//                    System.out.print(i+" ");

//                System.out.println();

int end =n-1;

long ans=0;

int r =-1;

                int beg =0;

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

{

    while(beg<=end&&dif[i]>x[beg])

    {

        r=beg;

        beg++;

    }

    end--;

r=Math.min(end,r);

    ans+=r+1;

}

                System.out.println(ans);

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

//    ///DFS To calculate the number of child nodes and depth in tree kind of structure

//    public static int dfs(ArrayList<ArrayList<Integer>> adj, int s, int d, int child[], int depth[]) {

//        depth[s] = d;

//        for(int v: adj.get(s)) {

//            if(depth[v] == -1) {

//                child[s] += dfs(adj, v, d+1, child, depth);

//            }

//        }

//        return child[s]+1;

//    }

    public static int dfs(ArrayList<ArrayList<Integer>> adj , int node,int dp[],int vis[]) {

        int ans=1;

        vis[node]=-1;

        if(dp[node]!=-1)

           return ans;

        for(int i :adj.get(node)) {

            if(vis[i]==-1)

            {

                return Integer.MIN_VALUE;

            }

else

    ans = ans +dfs(adj, i, dp,vis);

        }

        return dp[node]= ans ;

    }

    public static void sortby(int arr[][])

    {

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

            @Override

            // Compare values according to columns

            public int compare(final int[] entry1,

                               final int[] entry2) {

                // To sort in descending order revert

                // the '>' Operator

                if (entry1[1] >entry2[1])

                    return 1;

                else if(entry1[1]<entry2[1])

                    return -1;

                else if(entry1[2]>entry2[2])

                    return 1;

                else return -1;

            }

        });  // End of function call sort().

    }

    static long comb(int r, int n)

    {

        long result;

        result = factorial(n)/(factorial(r)*factorial(n-r));

        return result;

    }

    static long factorial(int n) {

        int c;

        long result = 1;

        for (c = 1; c <= n; c++)

            result = result*c;

        return result;

    }

    static void  LongestPalindromicPrefix(String str,int lps[]){

//        String temp = str + '/';

//        str = reverse(str);

//        temp += str;

        String temp =str;

        int n = temp.length();

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

        {

            int len = lps[i - 1];

            while (len > 0 && temp.charAt(len) !=

                    temp.charAt(i))

            {

                len = lps[len - 1];

            }

            if (temp.charAt(i) == temp.charAt(len))

            {

                len++;

            }

            lps[i] = len;

        }

//        return temp.substring(0, lps[n - 1]);

    }

    static String reverse(String input)

    {

        char[] a = input.toCharArray();

        int l, r = a.length - 1;

        for(l = 0; l < r; l++, r--)

        {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.valueOf(a);

    }

}

/*

 *

 *　　┏┓　　　┏┓+ +

 *　┏┛┻━━━┛┻┓ + +

 *　┃　　　　　　　┃

 *　┃　　　━　　　┃ ++ + + +

 *   ████━████+

 *  ◥██◤　◥██◤ +

 *　┃　　　┻　　　┃

 *　┃　　　　　　　┃ + +

 *　┗━┓　　　┏━┛

 *　　　┃　　┃      JACKS PET FROM ANOTHER WORLD

 *　　　┃　　┃

 *　　　┃　 　 ┗━━━┓

 *　　　┃ 　　　　　　 ┣┓-------

 *　　  ┃ 　　　　　 　┏┛-------

 *　    ┗┓┓┏━┳┓┏┛ + + + +

 *　　　　┃┫┫　┃┫┫

 *　　　　┗┻┛　┗┻┛+ + + +

 */

//RULES

//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array

//Always use stringbuilder of out.println for strinof out.println for string or high level output

// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN

//Read minute details if coming wrong for no idea questions


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

import java.util.*;

import java.io.*;

public class Main {

   static class FastReader{

	   BufferedReader br;

	   StringTokenizer st;

	   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;

	  }

   }

	static class Pair{

	//implements Comparable<Pair> {

		  long x;

		  long y;

		  Pair(long x,long y){

			  this.x=x;

			  this.y=y;

		  }

//		  @Override

//		  public int compareTo(Pair o) {

//			return this.y-o.y;

//		  }

		}

 static long gcd(long a,long b) {

	  if(b==0) return a;

	else

	  return gcd(b,a%b);

   }

 static List primeFactors(int n){

     List<Integer> ar=new ArrayList<>();

     int ct=0;

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

	    if(n%i==0) {

		  ar.add(i);

		  ct++;

	     while(n%i==0) {

	       n/=i;

	     }

       }

     }

    if(n>1) {

    	ct++;

	 ar.add(n);

    }

    return ar;

   }

 static int lb(ArrayList<Long>ar,long k) {

	int s=0;

	int e=ar.size();

	while(s!=e) {

	  int mid=s+e>>1;

	  if(ar.get(mid)<k)

		 s=mid+1;

	  else

		 e=mid;

     }

	if(s==0)

		return -1;

    return s-1;

  }

 static long powM(long x,long y,long mod) {

	if(y==0)

		return 1;

	long k=powM(x,y/2,mod);

	if(y%2==1) {

		return (((((long)1*k*k)%mod)*x)%mod);

	}

	else {

		return (((long)1*k*k)%mod);

	}

  }

 static int ub(ArrayList<Integer>ar,int k) {

	int s=0;

	int e=ar.size();

	while(s!=e) {

	  int mid=s+e>>1;

	  if(ar.get(mid)<=k)

		 s=mid+1;

	  else

		 e=mid;

     }

	if(s==ar.size())

		return -1;

    return s;

  }

 static boolean isPrime(long n) {

	 boolean flag=true;

	 if(n<2)

		 flag=false;

	 else {

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

			if(n%i==0) {

			 flag=false;

			 break;

			}

		 }

	 }

	 return flag;

 }

 static void pArray(int a[]) {

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

		 System.out.print(a[i]+" ");

     }

	 System.out.println();

 }

 static String sort(String s) {

	 char ch[]=s.toCharArray();

	 Arrays.sort(ch);

	 return new String(ch);

 }

// static int[] dij(int n,int src, ArrayList<Edge> ar[]) {

//	PriorityQueue<Pair>pq=new PriorityQueue<>();

//	pq.add(new Pair(src,0));

//	Set<Integer>vis=new HashSet<>();

//	int dist[]=new int[n+1];

//	dist[src]=0;

//	Arrays.fill(dist, Integer.MAX_VALUE);

//

//	while(pq.size()>0) {

//

//	  	Pair cur=pq.poll();

//	  	if(!vis.contains(cur.x)){

//

//	  		vis.add(cur.x);

//

//	  		dist[cur.x]=cur.y;

//

//	  	 for(Edge e:ar[cur.x]) {

//	  		 if(!vis.contains(e.dest)&&dist[e.dest]>cur.y+e.w )

//	  			pq.add(new Pair(e.dest,cur.y+e.w));

//	  	 }

//	  	}

//	  }

//	return dist;

// }

//

 public static String addCharToString(String str, char c,

         int pos)

{

StringBuffer stringBuffer = new StringBuffer(str);

stringBuffer.insert(pos, c);

return stringBuffer.toString();

}

 static int BigMod(String num, int a)

 {

    int res = 0;

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

         res = (res * 10 + (int)num.charAt(i));

    return res;

 }

 static boolean isSquare(int n) {

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

			if((i*i)==n)

				return true;

		}

		return false;

 }

 static long firstsetBitPower(long n)

 {

     int k = (int)(Math.log(n) / Math.log(2));

     return 1 << k;

 }

 public static void main(String[] args) {

 try {

  FastReader sc = new FastReader();

  //int t=sc.nextInt();

  //while(t-->0) {

    int n=sc.nextInt();

    int a[]=new int[n];

    int b[]=new int[n];

    for(int i=0;i<n;i++) a[i]=sc.nextInt();

    for(int i=0;i<n;i++) b[i]=sc.nextInt();

    int sec=0;

    int fir=0;

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

     if(a[i]!=b[i]) {

    	if(a[i]==1)

    		fir++;

    	else

    		sec++;

     }

    }

    if(fir==0&&sec==0) {

      	System.out.println("-1");

    }

    else if(fir==0) {

    	System.out.println("-1");

    }

    else if(fir>sec) {

       System.out.println("1");

    }

    else {

       System.out.println((sec/fir)+1);

    }

  //}

 }catch(Exception e) {return;}

 }

}

//https://www.codechef.com/MP3TO401?order=desc&sortBy=successful_submissions


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collections;

import java.util.StringTokenizer;

public class CollectingPackages {

    static PrintWriter pw;

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

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

        pw = new PrintWriter(System.out);

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

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

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

            ArrayList<Point> points = new ArrayList<>();

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

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

                int x = Integer.parseInt(st.nextToken());

                int y = Integer.parseInt(st.nextToken());

                points.add(new Point(x, y));

            }

            Collections.sort(points);

            if (!test(points)) {

                pw.println("NO");

            }

        }

        pw.close();

    }

    static boolean test(ArrayList<Point> points) {

        Point pos = new Point(0, 0);

        StringBuilder sb = new StringBuilder();

        for (Point p : points) {

            if (p.x >= pos.x && p.y >= pos.y) {

                sb.append(diff(pos, p));

                pos = p;

            } else return false;

        }

        pw.println("YES");

        pw.println(sb);

        return true;

    }

    static class Point implements Comparable<Point> {

        public int x, y;

        public Point(int x, int y) {

            this.x = x;

            this.y = y;

        }

        @Override

        public int compareTo(Point o) {

            int xComp = Integer.compare(x, o.x);

            if (xComp != 0) return xComp;

            else return Integer.compare(y, o.y);

        }

    }

    static StringBuilder diff(Point p1, Point p2) {

        int xDiff = p2.x - p1.x;

        int yDiff = p2.y - p1.y;

        StringBuilder res = new StringBuilder();

        res.append("R".repeat(Math.max(0, xDiff)));

        res.append("U".repeat(Math.max(0, yDiff)));

        return res;

    }

}


F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations:  Add 11 to the second element, making it equal to 99.  Subtract 11 from the third element, making it equal to 66.  Add 11 to the fifth element, making it equal to 22.  Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
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.Random;
import java.util.StringTokenizer;

public class F {

	static final int primes[] = new int[100000];
	static {
		primes[0] = 2;
		primes[1] = 3;
		long bitset[] = new long[7000];
		for (int i = 2, p = 1, dp = 4; i < primes.length; i++) {
			do {
				p += dp;
				dp = 6 - dp;
			} while ((bitset[(p / 3) >> 6] & (1L << (p / 3))) != 0);
			primes[i] = p;
			if (p <= 46340) {
				for (int q = p * p, dq = dp * p, l = 6 * p, j;
					(j = q / 3) >> 6 < bitset.length; q += dq, dq = l - dq) {
					bitset[j >> 6] |= 1L << j;
				}
			}
		}
	}

	static final long factors[] = new long[100];
	static int factorCount;

	static void addFactor(long p) {
		if (factorCount >= factors.length) {
			return;
		}
		for (int i = 0; i < factorCount; i++) {
			if (factors[i] == p) {
				return;
			}
		}
		factors[factorCount++] = p;
	}

	static void addFactors(long v) {
		for (long p: primes) {
			if (p * p > v) {
				break;
			}
			if (v % p == 0) {
				addFactor(p);
				do {
					v /= p;
				} while (v % p == 0);
			}
		}
		if (v > 1) {
			addFactor(v);
		}
	}

	static void solve() throws Exception {
//		System.err.println("START");
		int n = scanInt();
//		int n = 200000;
		long a[] = new long[n];
		long seed = 123;
//		Random trng = new Random();
		for (int i = 0; i < n; i++) {
			a[i] = scanLong();
//			a[i] = new BigInteger(40, 100, trng).longValue();
			seed = seed * 1000000009 ^ a[i];
		}
//		System.err.println("GEN");
		Random rng = new Random(seed);
		factorCount = 0;
		for (int i = 0; i < 100 && factorCount < factors.length; i++) {
			int j = rng.nextInt(n);
			addFactors(a[j]);
			addFactors(a[j] + 1);
			if (a[j] > 1) {
				addFactors(a[j] - 1);
			}
		}
//		System.err.println("FACT");
		long ans = n;
		i: for (int i = 0; i < factorCount; i++) {
			long p = factors[i];
			long cans = 0;
			for (int j = 0; j < n; j++) {
				long c = a[j], v;
				if (c < p) {
					v = p - c;
				} else {
					v = c % p;
					if (2 * v > p) {
						v = p - v;
					}
				}
				cans += v;
				if (cans >= ans) {
					continue i;
				}
			}
			ans = cans;
		}
//		System.err.println("CALC");
		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);
		}
	}
}


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

import java.util.*;

import java.io.*;

public class Main {

    static class Scan {

        private byte[] buf=new byte[1024];

        private int index;

        private InputStream in;

        private int total;

        public Scan()

        {

            in=System.in;

        }

        public int scan()throws IOException

        {

            if(total<0)

            throw new InputMismatchException();

            if(index>=total)

            {

                index=0;

                total=in.read(buf);

                if(total<=0)

                return -1;

            }

            return buf[index++];

        }

        public int scanInt()throws IOException

        {

            int integer=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n))

            {

                if(n>='0'&&n<='9')

                {

                    integer*=10;

                    integer+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            return neg*integer;

        }

        public double scanDouble()throws IOException

        {

            double doub=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n)&&n!='.')

            {

                if(n>='0'&&n<='9')

                {

                    doub*=10;

                    doub+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            if(n=='.')

            {

                n=scan();

                double temp=1;

                while(!isWhiteSpace(n))

                {

                    if(n>='0'&&n<='9')

                    {

                        temp/=10;

                        doub+=(n-'0')*temp;

                        n=scan();

                    }

                    else throw new InputMismatchException();

                }

            }

            return doub*neg;

        }

        public String scanString()throws IOException

        {

            StringBuilder sb=new StringBuilder();

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            while(!isWhiteSpace(n))

            {

                sb.append((char)n);

                n=scan();

            }

            return sb.toString();

        }

        private boolean isWhiteSpace(int n)

        {

            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)

            return true;

            return false;

        }

    }

    public static void sort(int arr[],int l,int r) {    //sort(arr,0,n-1);

        if(l==r) {

            return;

        }

        int mid=(l+r)/2;

        sort(arr,l,mid);

        sort(arr,mid+1,r);

        merge(arr,l,mid,mid+1,r);

    }

    public static void merge(int arr[],int l1,int r1,int l2,int r2) {

        int tmp[]=new int[r2-l1+1];

        int indx1=l1,indx2=l2;

        //sorting the two halves using a tmp array

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

            if(indx1>r1) {

                tmp[i]=arr[indx2];

                indx2++;

                continue;

            }

            if(indx2>r2) {

                tmp[i]=arr[indx1];

                indx1++;

                continue;

            }

            if(arr[indx1]<arr[indx2]) {

                tmp[i]=arr[indx1];

                indx1++;

                continue;

            }

            tmp[i]=arr[indx2];

            indx2++;

        }

        //Copying the elements of tmp into the main array

        for(int i=0,j=l1;i<tmp.length;i++,j++) {

            arr[j]=tmp[i];

        }

    }

    public static void sort(long arr[],int l,int r) {    //sort(arr,0,n-1);

        if(l==r) {

            return;

        }

        int mid=(l+r)/2;

        sort(arr,l,mid);

        sort(arr,mid+1,r);

        merge(arr,l,mid,mid+1,r);

    }

    public static void merge(long arr[],int l1,int r1,int l2,int r2) {

        long tmp[]=new long[r2-l1+1];

        int indx1=l1,indx2=l2;

        //sorting the two halves using a tmp array

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

            if(indx1>r1) {

                tmp[i]=arr[indx2];

                indx2++;

                continue;

            }

            if(indx2>r2) {

                tmp[i]=arr[indx1];

                indx1++;

                continue;

            }

            if(arr[indx1]<arr[indx2]) {

                tmp[i]=arr[indx1];

                indx1++;

                continue;

            }

            tmp[i]=arr[indx2];

            indx2++;

        }

        //Copying the elements of tmp into the main array

        for(int i=0,j=l1;i<tmp.length;i++,j++) {

            arr[j]=tmp[i];

        }

    }

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

        Scan input=new Scan();

        StringBuilder ans=new StringBuilder("");

        int n=input.scanInt();

        int m=input.scanInt();

        if(n==1) {

            if(m==0) {

                System.out.println(1);

                return;

            }

            System.out.println(-1);

            return;

        }

        int arr[]=new int[n];

        arr[0]=1;

        arr[1]=2;

        int freq[]=new int[50000001];

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

        freq[3]++;

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

            int ele=search(arr[i-1]+1,1000000000,m,freq,map);

            if(ele==-1) {

                break;

            }

            m-=get(ele,freq,map);

//            System.out.println(i+" "+ele);

            arr[i]=ele;

            add(arr,freq,i,map);

        }

        if(m!=0) {

            ans.append(-1);

        }

        else {

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

                ans.append(arr[i]+" ");

            }

        }

        System.out.println(ans);

    }

    public static int search(int l,int r,int m,int freq[],HashMap<Integer,Integer> map) {

        int ans=-1;

        while(l<=r) {

            int mid=(l+r)/2;

            int get=get(mid,freq,map);

            if(get<=m) {

                ans=mid;

                r=mid-1;

            }

            else {

                l=mid+1;

            }

        }

        return ans;

    }

    public static void add(int arr[],int freq[],int indx,HashMap<Integer,Integer> map) {

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

            add(arr[i]+arr[indx],freq,map);

        }

    }

    public static int get(int ele,int freq[],HashMap<Integer,Integer> map) {

        if(ele<freq.length) {

             return freq[ele];

        }

        if(!map.containsKey(ele)) {

            return 0;

        }

        return map.get(ele);

    }

    public static void add(int ele,int freq[],HashMap<Integer,Integer> map) {

        if(ele<freq.length) {

             freq[ele]++;

             return;

        }

        if(!map.containsKey(ele)) {

            map.put(ele, 0);

        }

        map.replace(ele, map.get(ele)+1);

    }

}


A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

import java.util.Scanner;

public class DeadPixel_1315A {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int t = s.nextInt();

        while(t-->0){

            int a = s.nextInt();

            int b = s.nextInt();

            int x = s.nextInt();

            int y = s.nextInt();

            int horizontal = Math.max(x,a-1-x);

            int vertical = Math.max(y,b-1-y);

            int a1 = horizontal*b;

            int a2 = vertical*a;

            System.out.println(Math.max(a1,a2));

        }

    }

}


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.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.*;

import java.util.Map.Entry;

 public class codeforces {

static int mod = 1000000007;

public static void main(String[] args) {

	  FastReader sc = new FastReader();

	  try {

          StringBuilder ss = new StringBuilder();

          int n =  sc.nextInt();

          String s = sc.next();

          int cnt = 0 ;

          int ans = 0;

          boolean flag =true;

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

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

        		  cnt++;

        	  }

          }

        	  cnt = 0;

        	  int cnt1 = 0;

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

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

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

        			  cnt++;

        		     int min = Math.min(cnt, cnt1);

        		    	ans += min;

        		    	cnt -= min;

        		    	cnt1 -= min;

                  }

        		  else {

        			  cnt1++;

        		 	  if(cnt>=cnt1) {

        		 		   int min = Math.min(cnt, cnt1);

        		 		  cnt -= min;

        		 		  cnt1 -= min;

        		 	  }

        		  }

        	  }

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

        	  if(cnt1 != 0 || cnt!= 0) {

        	ss.append(-1);

        	  }

        	  else {

        		  ss.append(2*ans);

        	  }

		  System.out.println(ss);

	      }

	      catch(Exception e) {

		  System.out.println(e.getMessage());

	      }

          }

 static long pow(long a, long b) {

	 long ans = 1;

	 long temp = a;

	 while(b>0) {

		 if((b&1) == 1) {

			 ans*=temp;

		 }

		 temp = temp*temp;

	  b = b>>1;

	 }

	 return ans;

 }

 static long ncr(int n, int r) {

	    return fact(n) / (fact(r) *

                fact(n - r));

}

static long fact(long n)

{

  long res = 1;

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

      res = (res * i);

  }

  return res;

}

 static long gcd(long a, long b) {

	 if(b == 0) {

		 return a;

	 }

	 return gcd(b , a%b);

 }

 static ArrayList<Integer> factor(long n) {

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

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

		 if(n%i == 0) {

			 if(n/i == i) {

				 al.add(i);

			 }

			 else {

				 al.add(i);

				 al.add((int) (n/i));

				 }

		 }

	 }

	 return al;

 }

 static class Pair implements Comparable<Pair>{

	 long a;

	 int b ;

	 Pair(long a, int b){

		 this.a = a;

		 this.b = b;

	 }

	@Override

	public int compareTo(Pair o) {

		// TODO Auto-generated method stub

	 return (int)(this.a - o.a);

	}

 }

 static ArrayList<Integer> sieve(int n) {

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

	 Arrays.fill(a, false);

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

		 if(!a[i]) {

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

				 a[j] = true;

			 }

		 }

	 }

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

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

		 if(!a[i]) {

			 al.add(i);

		 }

	 }

	 return al;

	}

 static ArrayList<Long> pf(long n) {

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

	 while(n%2 == 0) {

		 al.add(2l);

		 n = n/2;

	 }

	 for(long i = 3 ; i*i<=n ; i+=2) {

		 while(n%i == 0) {

			 al.add(i);

			 n = n/i;

		 }

	 }

	 if(n>2) {

		 al.add( n);

	 }

	 return al;

 }

 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;

     }

 }

 }


B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.

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

public class MaximalContinuousRest {
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int size = Integer.parseInt(br.readLine());
        int[] hours = new int[size * 2];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i = 0; i < size; i++){
            int currNum = Integer.parseInt(st.nextToken());
            hours[i] = currNum;
            hours[i + size] = currNum;
        }
        ArrayList<Integer> sizes = new ArrayList<>();
        int counter = 0;
        for(int i = 0; i < size * 2; i++){
            if(hours[i] == 0){
                sizes.add(counter);
                counter = 0;
            }
            else if(hours[i] == 1){
                counter++;
            }
        }
        int max = sizes.get(0);
        for(int i = 0; i < sizes.size(); i++){
            if(sizes.get(i) > max){
                max = sizes.get(i);
            }
        }
        System.out.println(max);
    }
}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import java.util.*;

public class Solution{

    public static void main(String[] args)

    {

        Scanner in=new Scanner(System.in);

        int n=in.nextInt();

        int m=in.nextInt();

        in.nextLine();

        String s1=in.nextLine();

        String s2=in.nextLine();

        String[] str1=s1.split(" ");

        String[] str2=s2.split(" ");

        int q=in.nextInt();

        for(int c=0;c<q;c++)

        {

            int x=in.nextInt();

            x=x-1;

            int i= x%n;

            int j=x%m;

            System.out.println(str1[i]+str2[j]);

        }

    }

}


B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.

import java.io.*;

import java.util.*;

import java.math.*;

public class Main{

	private static Scanner cin = new Scanner(new BufferedInputStream(System.in));

	private static PrintWriter cout = new PrintWriter(System.out,true);

	private static InputStream inputstream = System.in;

	private static FastScanner in = new FastScanner(inputstream);

	public static void main(String[] args){

		Task solver = new Task();

		int TaskCase = 1;

		while(TaskCase--!=0) solver.solve();

		cout.flush();

	}

	private static class Task{

		int n;

		Integer A[],C[];

		public void solve(){

			n = in.nextInt();

			A = new Integer[n];

			C = new Integer[n];

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

			int ans = 0;

			if((n&1)==0) for(int i = 0; i < n; i++) if((A[i]&1)==1) ans^=1;

			for(int bit = 1; bit < 25; bit++){

				if((n&1)==0) for(int i = 0; i < n; i++) if(((A[i])&(1<<bit))!=0) ans ^= (1<<bit);

				for(int i = 0; i < n; i++) C[i] = A[i] & ((1<<bit)-1);

				Arrays.sort(C);

				int ptr = n;

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

					if(ptr<=i) ptr = i + 1;

					while(ptr-1>i&&C[ptr-1]+C[i]>=(1<<bit)) ptr--;

					if(((n-ptr)&1)==1) ans ^= (1<<bit);

				}

			}

			cout.println(ans);

		}

	}

	public static class FastScanner {

		BufferedReader br;

		StringTokenizer st;

		public FastScanner(InputStream in) {

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

		}

		public int nextInt() {

			return Integer.parseInt(next());

		}

		public boolean hasMoreTokens() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

					return false;

				}

				if (line == null) {

					return false;

				}

				st = new StringTokenizer(line);

			}

			return true;

		}

		public String next() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

				}

				st = new StringTokenizer(line);

			}

			return st.nextToken();

		}

		public long nextLong() {

			return Long.parseLong(next());

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] ret = new int[n];

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

				ret[i] = nextInt();

			}

			return ret;

		}

		public long[] nextLongArray(int n) {

			long[] ret = new long[n];

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

				ret[i] = nextLong();

			}

			return ret;

		}

	}

}