E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int t=1;

//		t=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n= f.nextInt();

			int[] a=f.readArray(n);

			int[][] dp=new int[n][n];

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

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

				dp[i][i]=a[i];

			}

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

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

					dp[i][j]=-1;

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

						if(dp[i][k]!=-1 && dp[i][k]==dp[k+1][j])

							dp[i][j]=dp[i][k]+1;

					}

				}

			}

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

				dp2[i]=Integer.MAX_VALUE;

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

					if(dp[j][i-1]!=-1) {

						dp2[i]=Math.min(dp2[i], dp2[j]+1);

					}

				}

			}

			System.out.println(dp2[n]);

		}

		out.close();

	}

	static void sort(long[] p) {

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

        for (long i: p) q.add((int) i);

        Collections.sort(q);

        for (int i = 0; i < p.length; i++) p[i] = q.get(i);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

			for (int i=0; i<n; i++) a[i]=nextLong();

			return a;

		}

	}

}

//Some things to notice

//Check for the overflow

//Binary Search

//Bitmask

//runtime error most of the time is due to array index out of range


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

import java.io.*;

import java.util.*;

public class HelloWorld{

    static class Step{

        long no;

        String comm;

        Step(long no, String comm){

            this.no = no;

            this.comm = comm;

        }

    }

    private static ArrayList<Step> ls;

    private static long k;

    private static void check(){

        if(k > 0)   return;

        PrintWriter pw = new PrintWriter(System.out);

        pw.println("YES");

        pw.println(ls.size());

        for(Step step : ls)

            pw.println(+step.no+" "+step.comm);

        pw.flush();

        pw.close();

        System.exit(0);

    }

    private static void addStep(long no, String comm){

        if(no == 0 || comm.length() == 0)

            return;

        Step ns = new Step(no, comm);

        ls.add(ns);

        k -= no*comm.length();

        check();

        //System.out.println(+k);

    }

    public static void main(String []args){

        Scanner sc = new Scanner(System.in);

        int r = sc.nextInt(), c = sc.nextInt();

        k = sc.nextLong();

        long max = 4*r*c-2*r-2*c;

        if(k > max){

            System.out.println("NO");

            System.exit(0);

        }

        ls = new ArrayList<>();

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

            String sdir = (i%2 == 0)?"R":"L";

            long lim = Math.min(k, c-1);

            //System.out.println(+lim+" "+sdir);

            addStep(lim, sdir);

            if(i != r-1)

                addStep(1, "D");

        }

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

            String sdir = ((i+r)%2 == 1)?"UDL":"UDR";

            long lim = Math.min(k, 3*(c-1));

            addStep(lim/3, sdir);

            addStep(1, sdir.substring(0, (int)(lim%3)));

            addStep(1, "U");

        }

        addStep(k, "L");

    }

}


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

/* package codechef; // don't place package name! */

import java.util.*;

import java.lang.*;

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

public class Codechef

{

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

	{

		// your code goes here

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t-->0)

		{

		    long n=sc.nextLong();

		    while(n>1)

		    {

		    if(n%2==0)

		    {

		         System.out.print(1);

		         n=n-2;

		    }

		    else if(n==3)

		    {System.out.print("7");

		    break;}

		    else if (n%2==1)

		    {

		         n=n-3;

		         System.out.print("7");

		         n=n/2;

		         while(n-->0)

		         {

		              System.out.print("1");

		         }

		         break;

		    }

		    }

		    System.out.println();

		}

	}

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

// package codeforce.cf617;

import java.io.PrintWriter;

import java.util.*;

public class E2 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

//        int t = sc.nextInt();

        int t = 1;

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

            solve(sc, pw);

        }

        pw.close();

    }

    static void solve(Scanner in, PrintWriter out){

        int n = in.nextInt();

        char[] cs = in.next().toCharArray();

        int[] dp = new int[26];

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

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

            int idx = cs[i] - 'a';

            int state = 0;

            for (int j = idx + 1; j < 26; j++) {

                state |= dp[j];

            }

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

                if ((state | (1 << j)) != state){

                    ans.add(j + 1);

                    dp[idx] |= (1 << j);

                    break;

                }

            }

        }

        int st = 0;

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

            st |= dp[i];

        }

        int cnt = 0;

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

            if ((st | (1 << i)) == st){

                cnt++;

            }

        }

        out.println(cnt);

        for(int x : ans){

            out.print(x+" ");

        }

        out.println();

    }

    // Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2

    // worst case since it uses a version of quicksort. Although this would never

    // actually show up in the real world, in codeforces, people can hack, so

    // this is needed.

    static void ruffleSort(int[] a) {

        //ruffle

        int n=a.length;

        Random r=new Random();

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

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

            a[i]=a[oi];

            a[oi]=temp;

        }

        //then sort

        Arrays.sort(a);

    }

}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

//		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

		outer:for(int tt=0;tt<ttt;tt++) {

			int n=f.nextInt();

			double[] a=new double[n];

			for(int i=0;i<n;i++) a[i]=f.nextDouble();

			Stack<double[]> stack = new Stack();

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

				double sum = a[i];

				int len = 1;

				while (!stack.isEmpty()) {

					double[] top = stack.peek();

					if (sum / len > top[0]) {

						sum += top[0] * top[1];

						len += top[1];

						stack.pop();

					} else

						break;

				}

				double curr = sum / len;

				stack.push(new double[] { curr, len });

			}

			while (!stack.isEmpty()) {

				double[] curr = stack.pop();

				while (curr[1]-- > 0)

					out.println(curr[0]);

			}

		}

		out.close();

	}

	static void sort(int[] p) {

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

        for (int i: p) q.add( i);

        Collections.sort(q);

        for (int i = 0; i < p.length; i++) p[i] = q.get(i);

    }

    static long gcd(long a,long b) {

    	if(a==0) return b;

    	return gcd(b%a,a);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

			for (int i=0; i<n; i++) a[i]=nextLong();

			return a;

		}

	}

}


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

import java.util.*;

import java.io.*;

public class Practice {
	static boolean multipleTC = false;
	FastReader in;
	PrintWriter out;

	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 100005;

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

	void run() throws Exception {
		in = new FastReader();
		out = new PrintWriter(System.out);
		int T = (multipleTC) ? ni() : 1;
		pre();
		for (int t = 1; t <= T; t++)
			solve(t);
		out.flush();
		out.close();
	}

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni();
		char s[] = nln().toCharArray();
		int open = 0, close = 0;
		for (int i = 0; i < n; i++) {
			if (s[i] == '(') {
				open++;
			} else {
				close++;
			}
		}
		if (open != close) {
			pn("-1");
		} else {
			open = 0;
			close = 0;
			int res = 0;
			Stack<pair> st = new Stack<>();
			for (int i = 0; i < n; i++) {
				if (s[i] == ')' && !st.isEmpty() && st.peek().x == '(') {
					st.pop();
					if (s[i] == '(') {
						open++;
					} else {
						close++;
					}
					if (st.isEmpty()) {
						open = close = 0;
					}
				} else {
					st.push(new pair(s[i], i));
					if (s[i] == '(') {
						open++;
					} else {
						close++;
					}
					if (open == close) {

						res += (open + close);
						open = close = 0;
						st.clear();
					}
				}
			}
			pn(res);
		}
	}

	class pair {
		char x;
		int y;

		pair(char x, int y) {
			this.x = x;
			this.y = y;
		}

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

	}

	int[] readArr(int n) throws Exception {
		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = ni();
		}
		return arr;
	}

	void sort(int arr[]) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = 0; i < arr.length; i++)
			arr[i] = list.get(i);
	}

	public long max(long... arr) {
		long max = arr[0];
		for (long itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public int max(int... arr) {
		int max = arr[0];
		for (int itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public long min(long... arr) {
		long min = arr[0];
		for (long itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public int min(int... arr) {
		int min = arr[0];
		for (int itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public long sum(long... arr) {
		long sum = 0;
		for (long itr : arr)
			sum += itr;
		return sum;
	}

	public long sum(int... arr) {
		long sum = 0;
		for (int itr : arr)
			sum += itr;
		return sum;
	}

	String bin(long n) {
		return Long.toBinaryString(n);
	}

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

	static int bitCount(int x) {
		return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
	}

	static void dbg(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}

	int bit(long n) {
		return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
	}

	int abs(int a) {
		return (a < 0) ? -a : a;
	}

	long abs(long a) {
		return (a < 0) ? -a : a;
	}

	void p(Object o) {
		out.print(o);
	}

	void pn(Object o) {
		out.println(o);
	}

	void pni(Object o) {
		out.println(o);
		out.flush();
	}

	String n() throws Exception {
		return in.next();
	}

	String nln() throws Exception {
		return in.nextLine();
	}

	int ni() throws Exception {
		return Integer.parseInt(in.next());
	}

	long nl() throws Exception {
		return Long.parseLong(in.next());
	}

	double nd() throws Exception {
		return Double.parseDouble(in.next());
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}
	}
}


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

import java.io.*;

import java.math.*;

import java.util.*;

// @author : Dinosparton

public class test {

	static class Pair {

		Double x;

		int y;

		Pair(Double x, int y) {

			this.x = x;

			this.y = y;

		}

	}

	static class Compare {

		void compare(Pair arr[], int n) {

			// Comparator to sort the pair according to second element

			Arrays.sort(arr, new Comparator<Pair>() {

				@Override

				public int compare(Pair p1, Pair p2) {

					if (p1.x != p2.x) {

						return (int) (p1.x - p2.x);

					} else {

						return (int) (p1.y - p2.y);

					}

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

				}

			});

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

//		            System.out.print(arr[i].x + " " + arr[i].y + " ");

//		        }

//		        System.out.println();

		}

	}

	static class Scanner {

		BufferedReader br;

		StringTokenizer st;

		public Scanner() {

			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 int dp[][][][];

	static int recursion(int p[], int index,int odd,int even,int last) {

		if (index == p.length) {

			return 0;

		}

		if(dp[index][odd][even][last] != -1) {

			return dp[index][odd][even][last];

		}

		if(p[index] == 0) {

			int pos1 = 1000;

			int pos2 = 1000;

			if(odd > 0) {

				 pos1 = (last!=0 && last == 1 ? 0 : 1) + recursion(p,index+1,odd-1,even,1);

			}

			if(even > 0) {

				 pos2 = (last!=0 && last == 2 ? 0 : 1) + recursion(p,index+1,odd,even-1,2);

			}

			return dp[index][odd][even][last] = Math.min(pos1, pos2);

		}

		return dp[index][odd][even][last] = (last!=0 && last == p[index] ? 0 : 1) + recursion(p,index+1,odd,even,p[index]);

	}

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

		Scanner sc = new Scanner();

		StringBuilder res = new StringBuilder();

		int tc = 1;

		while (tc-- > 0) {

			int n = sc.nextInt();

			int p[] = new int[n];

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

				p[i] = sc.nextInt();

			}

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

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

				if (p[i] != 0) {

					visit[p[i]] = true;

				}

			}

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

				if (p[i] == 0) {

					continue;

				} else {

					p[i] = (p[i] % 2 == 0) ? 2 : 1;

				}

			}

			int odd = 0;

			int even = 0;

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

				if (!visit[i]) {

					if (i % 2 == 0) {

						even++;

					} else {

						odd++;

					}

				}

			}

			dp = new int[n+1][odd + 1][even + 1][3];

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

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

					for (int k = 0; k <= even; k++) {

						for(int l=0;l<3;l++) {

							dp[i][j][k][l] = -1;

						}

					}

				}

			}

//            System.out.println(odd);

			res.append(recursion(p, 0,odd,even,0) - 1 + "\n");

		}

		System.out.println(res);

	}

}


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

/*

    Author: Anthony Ngene

    Created: 05/10/2020 - 14:12

*/

import java.io.*;

import java.util.*;

public class F {

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

    void solver() throws IOException {

        int n = in.intNext();

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

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

        Integer best = null;

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

            int total = 0;

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

                total += arr[j];

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

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

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

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

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

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

                    best = total;

            }

        }

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

        out.println(bestList.size());

        for (Tuple aa: bestList)

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

    }

// Generated Code Below:

private static final FastWriter out = new FastWriter();

private static FastScanner in;

static ArrayList<Integer>[] adj;

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

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

    in = new FastScanner();

    new F().solver();

    out.close();

}

static class FastWriter {

    private static final int IO_BUFFERS = 128 * 1024;

    private final StringBuilder out;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public void toFile(String fileName) throws IOException {

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

        writer.write(out.toString());

        writer.close();

    }

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

}

static class FastScanner {

    private InputStream sin = System.in;

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

    private int ptr = 0;

    private int buflen = 0;

    public FastScanner(){}

    public FastScanner(String filename) throws FileNotFoundException {

        File file = new File(filename);

        sin = new FileInputStream(file);

    }

    private boolean hasNextByte() {

        if (ptr < buflen) {

            return true;

        }else{

            ptr = 0;

            try {

                buflen = sin.read(buffer);

            } catch (IOException e) {

                e.printStackTrace();

            }

            if (buflen <= 0) {

                return false;

            }

        }

        return true;

    }

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

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

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

    public String next() {

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

        StringBuilder sb = new StringBuilder();

        int b = readByte();

        while(isPrintableChar(b)) {

            sb.appendCodePoint(b);

            b = readByte();

        }

        return sb.toString();

    }

    public long longNext() {

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

        long n = 0;

        boolean minus = false;

        int b = readByte();

        if (b == '-') {

            minus = true;

            b = readByte();

        }

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

            throw new NumberFormatException();

        }

        while(true){

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

                n *= 10;

                n += b - '0';

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

                return minus ? -n : n;

            }else{

                throw new NumberFormatException();

            }

            b = readByte();

        }

    }

    public int intNext() {

        long nl = longNext();

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

        return (int) nl;

    }

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

    public long[] nextLongArray(final int n){

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

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

            a[i] = longNext();

        return a;

    }

    public int[] nextIntArray(final int n){

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

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

            a[i] = intNext();

        return a;

    }

    public double[] nextDoubleArray(final int n){

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

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

            a[i] = doubleNext();

        return a;

    }

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

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

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

        return adj;

    }

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

        return adjacencyList(nodes, edges, false);

    }

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

        adj = getAdj(nodes);

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

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

            adj[a].add(b);

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

        }

        return adj;

    }

}

static class u {

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

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

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

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

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

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

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

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

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

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

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

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

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

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

            }

        });

    }

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

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

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

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

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

        while (left < right) {

            int temp = arr[left];

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

            arr[right--] = temp;

        }

        return arr;

    }

    public static boolean findNextPermutation(int[] data) {

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

        int last = data.length - 2;

        while (last >= 0) {

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

            last--;

        }

        if (last < 0) return false;

        int nextGreater = data.length - 1;

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

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

                nextGreater = i;

                break;

            }

        }

        data = swap(data, nextGreater, last);

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

        return true;

    }

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

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

        int mid=-1;

        while(left<=right){

            mid = (right+left)/2;

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

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

            else right=mid-1;

        }

        return -1;

    }

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

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

        int mid=-1;

        while((right-left)>1){

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

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

            else right=mid;

        }

        return left;

    }

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

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

        int mid=-1;

        while((right-left)>1){

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

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

            else right=mid;

        }

        return left;

    }

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

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

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

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

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

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

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

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

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

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

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

        if(a!=b) return false;

        if(b!=c) return false;

        if(c!=a) return false;

        return true;

    }

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

        if(a==b) return false;

        if(b==c) return false;

        if(c==a) return false;

        return true;

    }

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

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

    }

    private static long factorial(int n) {

        long ans=1;

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

        return ans;

    }

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

        long ans=1;

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

        return ans;

    }

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

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

        ans *= n;

        return ans;

    }

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

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

        if(n == 0) return m;

        return gcd(n, m % n);

    }

    private static boolean isPrime(long a){

        if(a==1) return false;

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

        return true;

    }

    static long modInverse(long a, long mod) {

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

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

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

    }

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

        long res = 1;

        while (b > 0) {

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

            a = (a * a) % mod;

            b /= 2;

        }

        return res;

    }

    private static int getDigit2(long num){

        long cf = 1;    int d=0;

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

        return d;

    }

    private static int getDigit10(long num){

        long cf = 1;    int d=0;

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

        return d;

    }

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

        if(y<0) return false;

        if(x<0) return false;

        if(y>=h) return false;

        if(x>=w) return false;

        return true;

    }

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

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

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

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

            if (lp[i] == 0) {

                lp[i] = i;

                pr.add(i);

            }

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

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

            }

        }

        return pr;

    }

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

        long res = 1;

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

            res = (res * i) % MOD;

        }

        return res;

    }

    static long nCr(int n, int r) {

        if (r > (n - r))

            r = n - r;

        long ans = 1;

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

            ans *= n;

            ans /= i;

            n--;

        }

        return ans;

    }

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

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

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

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

        return  (first * second) % MOD;

    }

    static void printBitRepr(int n) {

        StringBuilder res = new StringBuilder();

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

            int mask = (1 << i);

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

        }

        out.println(res);

    }

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

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

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

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

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

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

    static long hash(int x, int y) {

        return x* 1_000_000_000L +y;

    }

    static final Random random = new Random();

    static void sort(int[] a) {

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

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

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

            a[oi] = a[i];

            a[i] = temp;

        }

        Arrays.sort(a);

    }

    static void sort(long[] arr) {

        shuffleArray(arr);

        Arrays.sort(arr);

    }

    static void shuffleArray(long[] arr) {

        int n = arr.length;

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

            long tmp = arr[i];

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

            arr[i] = arr[randomPos];

            arr[randomPos] = tmp;

        }

    }

}

static class Tuple implements Comparable<Tuple> {

    int a;

    int b;

    int c;

    public Tuple(int a, int b) {

        this.a = a;

        this.b = b;

        this.c = 0;

    }

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

        this.a = a;

        this.b = b;

        this.c = c;

    }

    public int getA() { return a; }

    public int getB() { return b; }

    public int getC() { return c; }

    public int compareTo(Tuple other) {

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

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

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

        }

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

    }

    @Override

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

    @Override

    public boolean equals(Object o) {

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

        Tuple pairo = (Tuple) o;

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

    }

    @Override

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

}

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

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

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

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

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

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

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

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

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

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

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

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

}


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

import java.io.*;

import java.util.*;

/*

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

// Demonstrating Set using HashSet

        // Declaring object of type String

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

        // Adding elements to the Set

        // using add() method

        hash_Set.add("Geeks");

        hash_Set.add("For");

        hash_Set.add("Geeks");

        hash_Set.add("Example");

        hash_Set.add("Set");

        // Printing elements of HashSet object

        System.out.println(hash_Set);

 */

public class Main {

    static boolean flag = false;

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

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

    static StringTokenizer tok;

    public static void check() throws IOException {

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

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

    }

    public static int nextInt() throws IOException {

        return Integer.parseInt(nextString());

    }

    public static long nextLong() throws IOException {

        return Long.parseLong(nextString());

    }

    public static double nextDouble() throws IOException {

        return Double.parseDouble(nextString());

    }

    public static String nextString() throws IOException {

        check();

        return tok.nextToken();

    }

    public static void println(Object o) {

        out.println(o);

        out.flush();

    }

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

        int[] a = new int[n];

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

            a[i] = nextInt();

        return a;

    }

    static int findLCM(int x, int y) {

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

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

    }

    static int findGCD(int x, int y) {

        int r = 0, a, b;

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

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

        r = b;

        while (a % b != 0) {

            r = a % b;

            a = b;

            b = r;

        }

        return r;

    }

    /*

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

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

                primes[i] =true;

            }

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

                if(primes[i] == true){

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

                        primes[j] =false;

                    }

                }

            }

     */

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

        Scanner input = new Scanner(System.in);

        int t = input.nextInt();

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

        int lCounter = 0;

        int rCounter = 0;

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

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

                lCounter++;

            else

                rCounter++;

        }

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

        out.flush();

        out.close();

    }

    }

/*

5

*

* *

* * *

* * * *

* * * * *

 */

/*

5

*

* *

* * *

* * * *

* * * * *

 */

/*

input:5

output:

*

**

***

****

*****

 */


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

// package c1311;

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

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

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

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

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

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

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

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

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

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

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

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

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

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

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

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

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


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

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.lang.invoke.MethodHandles;

import java.util.*;

public class b {

	public static void main(String []args) {

		MyScanner s=new MyScanner();

	int n=s.nextInt();

		long a=s.nextLong();

		long b=s.nextLong();

		long k=s.nextLong();

		long []f=new long [n];

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

			f[i]=s.nextLong();

		long []t=new long [n];

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

			if(f[i]<=a)

			{

				t[i]=0;

			}

			else if(f[i]>a) {

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

				 if(c==0) {

					 long e=b/a;

					 if(b%a!=0)

						 e++;

					 t[i]=e;

				 }

				 else {

					 long d=c/a;

					 if(c%a!=0)

						 d++;

					 if(d>1)

					 t[i]=d-1;

					 else t[i]=0;

				 }

			 }

		}

		Arrays.sort(t);

		int res=0;

		for(long x:t) {

			if(k-x>=0) {

				res++;

				k=k-x;

			}

			// System.out.println(x);

		}

			 System.out.println(res);

	}

	public static  boolean is(String s) {

		int l=0;

		int r=s.length()-1;

		while(l<r) {

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

				return false;

			l++;r--;

		}

		return true;

	}

	public static void  shufu(int []f) {

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

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

			int k=f[t];

			f[t]=f[i];

			f[i]=k;

		}

	}

	static class MyScanner {

	    BufferedReader br;

	    StringTokenizer st;

	    public MyScanner() {

	      try {

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

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

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

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

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

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

	      } catch (Exception e) {

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

	      }

	    }

	    public String next() {

	      try {

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

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

	        }

	        return st.nextToken();

	      } catch (Exception e) {

	        throw new RuntimeException(e);

	      }

	    }

	    public int nextInt() {

	      return Integer.parseInt(next());

	    }

	    public long nextLong() {

	      return Long.parseLong(next());

	    }

	  }

		}


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

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

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

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

    long[][] dp;

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

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

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

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

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

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

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

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

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

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

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

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

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

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


import java.util.*;

public class UnusualCompetitions {

	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);

		int n=sc.nextInt();

		String s=sc.next();

		char crr[]=s.toCharArray();

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

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

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

				o++;

			}

			else {

				c++;

			}

		}

		if(o!=c) {

			System.out.println(-1);

			return;

		}

		o=0;

		c=0;

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

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

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

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

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

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

						o++;

					}

					else {

						c++;

					}

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

					if(o==c) {

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

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

						ans+=(j-pos)+1;

						i=j;

						pos=-1;

						c=0;

						o=0;

						break;

					}

				}

			}

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

				o++;

			}

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

				o--;

			}

			else {

				c++;

				if(pos==-1) {

					pos=i;

				}

			}

		}

		System.out.println(ans);

	}

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

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

        Reader input = new Reader();

        int n = input.nextInt();

        int[] a = new int[n];

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

            a[i] = input.nextInt();

        }

        int maxBit = getMaxBit(a);

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

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

    }

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

        int answer = 0;

        while(mask > 0) {

            int zeros = 0;

            int ones = 0;

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

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

                    ++ones;

                } else {

                    ++zeros;

                }

            }

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

                answer |= mask;

                int[] g1 = new int[ones];

                int[] g2 = new int[zeros];

                int onesPointer = 0, zerosPointer = 0;

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

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

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

                    } else {

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

                    }

                }

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

                if(temp1 < temp2) {

                    answer = answer|temp1;

                } else {

                    answer = answer|temp2;

                }

                break;

            }

            mask = mask >> 1;

        }

        return answer;

    }

    static int getMaxBit(int[] a) {

        int max = a[0];

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

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

        }

        int bits = 0;

        while(max > 0) {

            ++bits;

            max = max>>1;

        }

        return bits;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


import java.util.*;

public class Ap {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		int n = s.nextInt();

		String str = s.next();

		int sum=0;

		int pos=0;

		int co=0;

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

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

				sum++;

			}

			else {

				sum--;

			}

			if(sum<0) {

				co++;

			}

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

				co++;

			}

			pos=sum;

		}

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

		else {

			System.out.println(co);

		}

	}

}


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

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class cdf626b

{

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

	{

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

		if(n>arr.length)

			return 0;

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

		{

			if(arr[i]!=0)

				cou1++;

			if(cou1==n)

			{

				tot1++;

				cou1--;

			}

			if(arr[i]==0)

				cou1=0;

		}

		return tot1;

	}

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

	{

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

		String s=br.readLine();

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

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

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

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

		s=br.readLine();

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

		int arr[]=new int[n];

		long o1=0,o2=0;

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

		{

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

			if(arr[j]==1)

				o1++;

		}

		s=br.readLine();

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

		int arr1[]=new int[m];

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

		{

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

			if(arr1[j]==1)

				o2++;

		}

		long copy=k,tempo=1;

		long ans=0;

		if(k==1)

		{

			ans=o1*o2;

			System.out.print(ans);

			return;

		}

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

		{

			if(k%i!=0)

			continue;

			if(i*i==k)

			{

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

				break;

			}

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

		}

		System.out.println(ans);

	}

}