A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

import java.awt.*;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.math.BigInteger;

import java.util.*;

import java.util.List;

public class erasingzeroes {

    static int mod = (int) 1e9 + 7;

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int t=sc.nextInt();

        while(t-->0){

            String s=sc.next();

            boolean z=false;

            int first=s.length();

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

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

                    first=i;

                    break;

                }

            }

            int last=-1;

            for(int i=s.length()-1;i>=0;i--){

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

                    last=i;

                    break;

                }

            }

            int total=0;

            for(int i=first;i<=last;i++){

                if(s.charAt(i)=='0')total++;

            }

            System.out.println(total);

        }

    }

}


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.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 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

import java.util.Scanner;
public class template {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            solve();
        }
    }
    public static void solve() {
        int n = sc.nextInt();
        int[] input = new int[n];
        for (int i = 0; i < n; i++) {
            input[i] = sc.nextInt();
        }
        int even = input[0] % 2;
        for (int i = 0; i < n; i++) {
            if (input[i] % 2 != even) {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
        return;
    }
}


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class AnotA {

	long x1,x2;

	long y1,y2;

	AnotA(String s){

		StringTokenizer st = new StringTokenizer(s);

		this.x1 =Integer.parseInt(st.nextToken());

		this.y1 =Integer.parseInt(st.nextToken());

		this.x2 =Integer.parseInt(st.nextToken());

		this.y2 =Integer.parseInt(st.nextToken());

	}

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

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

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

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

			AnotA a = new AnotA(br.readLine());

			AnotA b = new AnotA(br.readLine());

			AnotA c = new AnotA(br.readLine());

			System.out.println(CC(a,b,c)||CC(b,c,a)||CC(c,a,b)?"YES":"NO");

		}

	}

	public static boolean CC(AnotA a, AnotA b, AnotA c) {

		return checkConstraints(a,b,c)&&(

				checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||

				checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));

	}

	//Took Dukkha code as reference

	private static boolean checkIntersection(long x, long y, AnotA a) {

		//check if the point is lying outside the segment

		if(x<Math.min(a.x1, a.x2)||x>Math.max(a.x1, a.x2)||y<Math.min(a.y1, a.y2)||y>Math.max(a.y1, a.y2))

			return false;

		//check ratio between parts

		int xpart = (int) Math.abs(a.x1-a.x2);

		int ypart = (int) Math.abs(a.y1-a.y2);

		int xmin = (int) Math.min(Math.abs(a.x1-x), Math.abs(a.x2-x));

		int ymin = (int) Math.min(Math.abs(a.y1-y), Math.abs(a.y2-y));

		return xpart<=5*xmin&&ypart<=5*ymin&& (long) (x-a.x2)*(a.y1-a.y2)==(long)(y-a.y2)*(a.x1-a.x2);

	}

	public static boolean checkConstraints(AnotA a, AnotA b, AnotA c) {

		if(a.x1==b.x1&&a.y1==b.y1) {

			return getAngle(a.x2,a.y2,b.x2,b.y2,a.x1,a.y1);

		}

		else if(a.x2==b.x1&&a.y2==b.y1) {

			return getAngle(a.x1, a.y1, b.x2, b.y2, a.x2, a.y2);

		}

		else if(a.x1==b.x2&&a.y1==b.y2) {

			return getAngle(a.x2, a.y2, b.x1, b.y1, a.x1, a.y1);

		}

		else if(a.x2==b.x2&&a.y2==b.y2) {

			return getAngle(a.x1, a.y1, b.x1, b.y1, a.x2, a.y2);

		}

		return false;

	}

	public static boolean getAngle(long x1, long y1, long x2, long y2, long x3, long y3) {

		boolean collinear =areCollinear( x1,  y1,  x2,  y2,  x3,  y3);

		//check angle <= 90

		long a13 = (long) (x1-x3) * (x1-x3) + (long) (y1-y3) *(y1-y3);

		long a23 = (long) (x2-x3) * (x2-x3) + (long) (y2-y3) *(y2-y3);

		long a12 = (long) (x1-x2) * (x1-x2) + (long) (y1-y2) *(y1-y2);

		return !collinear&&a13+a23>=a12;

	}

	private static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {

		long area = (long) (x1-x3)*(y2-y3) - (long) (x2-x3)*(y1-y3);

		return area==0?true:false;

	}

}


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.math.BigDecimal;

import java.math.RoundingMode;

import java.util.*;

import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import java.beans.Visibility;

import java.io.File;

import java.io.FileDescriptor;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.io.UncheckedIOException;

import java.lang.Thread.State;

import java.lang.reflect.Field;

import java.nio.CharBuffer;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.CharsetEncoder;

import java.nio.charset.StandardCharsets;

public class Main {

	static final long MOD1=1000000007;

	static final long MOD=998244353;

	static long ans=0;

	public static void main(String[] args){

		PrintWriter out = new PrintWriter(System.out);

		InputReader sc=new InputReader(System.in);

		int n  = sc.nextInt();

		int m = sc.nextInt();

		int[] a = sc.nextIntArray(m);

		int[] min = new int[n];

		int[] max = new int[n];

		Arrays.setAll(min, k->k+1);

		Arrays.setAll(max, k->k+1);

		int[] last = new int[n];

		Arrays.fill(last, -1);

		SegTree<Integer> seg1 = new SegTree<Integer>(n, (x,y)->x+y, 0);

		SegTree<Integer> seg2 = new SegTree<Integer>(m, (x,y)->x+y, 0);

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

			int id = a[i]-1;

			min[id] = 1;

			if (last[id]==-1) {

				max[id] += seg1.prod(a[i], n);

				seg1.set(id, 1);

				seg2.set(i, 1);

			}else {

				seg2.set(last[id], 0);

				seg2.set(i, 1);

				max[id] = Math.max(max[id], seg2.prod(last[id], i)+1);

			}

			last[id] = i;

		}

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

			if (last[i]==-1) {

				max[i] += seg1.prod(i, n);

			}else {

				max[i] = Math.max(max[i], seg2.prod(last[i], m));

			}

		}

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

			out.println(min[i]+" "+max[i]);

		}

		out.flush();

	}

	static class SegTree<S> {

	    final int MAX;

	    final int N;

	    final java.util.function.BinaryOperator<S> op;

	    final S E;

	    final S[] data;

	    @SuppressWarnings("unchecked")

	    public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) {

	        this.MAX = n;

	        int k = 1;

	        while (k < n) k <<= 1;

	        this.N = k;

	        this.E = e;

	        this.op = op;

	        this.data = (S[]) new Object[N << 1];

	        java.util.Arrays.fill(data, E);

	    }

	    public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) {

	        this(dat.length, op, e);

	        build(dat);

	    }

	    private void build(S[] dat) {

	        int l = dat.length;

	        System.arraycopy(dat, 0, data, N, l);

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

	            data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]);

	        }

	    }

	    public void set(int p, S x) {

	        exclusiveRangeCheck(p);

	        data[p += N] = x;

	        p >>= 1;

	        while (p > 0) {

	            data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]);

	            p >>= 1;

	        }

	    }

	    public S get(int p) {

	        exclusiveRangeCheck(p);

	        return data[p + N];

	    }

	    public S prod(int l, int r) {

	        if (l > r) {

	            throw new IllegalArgumentException(

	                String.format("Invalid range: [%d, %d)", l, r)

	            );

	        }

	        inclusiveRangeCheck(l);

	        inclusiveRangeCheck(r);

	        S sumLeft = E;

	        S sumRight = E;

	        l += N; r += N;

	        while (l < r) {

	            if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]);

	            if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight);

	            l >>= 1; r >>= 1;

	        }

	        return op.apply(sumLeft, sumRight);

	    }

	    public S allProd() {

	        return data[1];

	    }

	    public int maxRight(int l, java.util.function.Predicate<S> f) {

	        inclusiveRangeCheck(l);

	        if (!f.test(E)) {

	            throw new IllegalArgumentException("Identity element must satisfy the condition.");

	        }

	        if (l == MAX) return MAX;

	        l += N;

	        S sum = E;

	        do {

	            l >>= Integer.numberOfTrailingZeros(l);

	            if (!f.test(op.apply(sum, data[l]))) {

	                while (l < N) {

	                    l = l << 1;

	                    if (f.test(op.apply(sum, data[l]))) {

	                        sum = op.apply(sum, data[l]);

	                        l++;

	                    }

	                }

	                return l - N;

	            }

	            sum = op.apply(sum, data[l]);

	            l++;

	        } while ((l & -l) != l);

	        return MAX;

	    }

	    public int minLeft(int r, java.util.function.Predicate<S> f) {

	        inclusiveRangeCheck(r);

	        if (!f.test(E)) {

	            throw new IllegalArgumentException("Identity element must satisfy the condition.");

	        }

	        if (r == 0) return 0;

	        r += N;

	        S sum = E;

	        do {

	            r--;

	            while (r > 1 && (r & 1) == 1) r >>= 1;

	            if (!f.test(op.apply(data[r], sum))) {

	                while (r < N) {

	                    r = r << 1 | 1;

	                    if (f.test(op.apply(data[r], sum))) {

	                        sum = op.apply(data[r], sum);

	                        r--;

	                    }

	                }

	                return r + 1 - N;

	            }

	            sum = op.apply(data[r], sum);

	        } while ((r & -r) != r);

	        return 0;

	    }

	    private void exclusiveRangeCheck(int p) {

	        if (p < 0 || p >= MAX) {

	            throw new IndexOutOfBoundsException(

	                String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)

	            );

	        }

	    }

	    private void inclusiveRangeCheck(int p) {

	        if (p < 0 || p > MAX) {

	            throw new IndexOutOfBoundsException(

	                String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)

	            );

	        }

	    }

	}

	static class InputReader {

		private InputStream in;

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

		private int curbuf;

		private int lenbuf;

		public InputReader(InputStream in) {

			this.in = in;

			this.curbuf = this.lenbuf = 0;

		}

		public boolean hasNextByte() {

			if (curbuf >= lenbuf) {

				curbuf = 0;

				try {

					lenbuf = in.read(buffer);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (lenbuf <= 0)

					return false;

			}

			return true;

		}

		private int readByte() {

			if (hasNextByte())

				return buffer[curbuf++];

			else

				return -1;

		}

		private boolean isSpaceChar(int c) {

			return !(c >= 33 && c <= 126);

		}

		private void skip() {

			while (hasNextByte() && isSpaceChar(buffer[curbuf]))

				curbuf++;

		}

		public boolean hasNext() {

			skip();

			return hasNextByte();

		}

		public String next() {

			if (!hasNext())

				throw new NoSuchElementException();

			StringBuilder sb = new StringBuilder();

			int b = readByte();

			while (!isSpaceChar(b)) {

				sb.appendCodePoint(b);

				b = readByte();

			}

			return sb.toString();

		}

		public int nextInt() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			int res = 0;

			do {

				if (c < '0' || c > '9')

					throw new InputMismatchException();

				res = res * 10 + c - '0';

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public long nextLong() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			long res = 0;

			do {

				if (c < '0' || c > '9')

					throw new InputMismatchException();

				res = res * 10 + c - '0';

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		public double[] nextDoubleArray(int n) {

			double[] a = new double[n];

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

				a[i] = nextDouble();

			return a;

		}

		public long[] nextLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		public char[][] nextCharMap(int n, int m) {

			char[][] map = new char[n][m];

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

				map[i] = next().toCharArray();

			return map;

		}

	}

}


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.StringTokenizer;

public class cf {

	static class FastReader {

		BufferedReader br;

		StringTokenizer st;

		public FastReader() {

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

		}

		String next() {

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

				try {

					String str = br.readLine();

					if(str == null)

						throw new InputMismatchException();

					st = new StringTokenizer(str);

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

			}

			if(str == null)

				throw new InputMismatchException();

			return str;

		}

	}

    static boolean pal(String s)

    {

    	StringBuilder sb=new StringBuilder();

    	sb.append(s);

    	sb.reverse();

    	String s1=sb.toString();

    	if(s1.contentEquals(s))

    	{

    		return true;

    	}

    	else

    	{

    		return false;

    	}

    }

    static boolean isPrime(long arr)

{

    // Corner cases

    if (arr <= 1)

        return false;

    if (arr <= 3)

        return true;

    // This is checked so that we can skip

    // middle five numbers in below loop

    if (arr % 2 == 0 || arr % 3 == 0)

        return false;

    for (int i = 5; i * i <= arr; i = i + 6)

        if (arr % i == 0 || arr % (i + 2) == 0)

            return false;

    return true;

}

    public static int reverseBits(int n)

    {

        int rev = 0;

        // traversing bits of 'n'

        // from the right

        while (n > 0)

        {

            // bitwise left shift

            // 'rev' by 1

            rev <<= 1;

            // if current bit is '1'

            if ((int)(n & 1) == 1)

                rev ^= 1;

            // bitwise right shift

            //'n' by 1

            n >>= 1;

        }

        // required number

        return rev;

    }

    static int fact(int n)

    {

    	int fact=1;

    	while(n>=1)

    	{

    		fact=fact*n;

    		n--;

    	}

    	return fact;

    }

    static long __gcd(long a, long b)

    {

        if (a == 0 || b == 0)

            return 0;

        if (a == b)

            return a;

        if (a > b)

            return __gcd(a-b, b);

        return __gcd(a, b-a);

    }

    static boolean coprime(long a, long b) {

        if ( __gcd(a, b) == 1)

            return true;

        else

            return false;

    }

    static int xor(int n,int a,int b)

    {

		if(n>0)

		{

			xor(n-1,b,a^b);

			return a^b;

		}

		else

		{

			return a^b;

		}

    }

	public static void main(String[] args)

	{

		FastReader sc = new FastReader();

	    PrintWriter out = new PrintWriter(System.out);

//        int t=sc.nextInt();

//        while(t-->0)

//        {

//

//        }

	    String s=sc.next();

	    int n=s.length();

	    int l=s.indexOf('(');

	    int r=s.lastIndexOf(')');

	    int c1=1,c2=1;

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

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

	    if(l<r)

	    {

		    x1.add(l);

		    x2.add(r);

	    }

	    l++;

	    r--;

	    while(l<=r)

	    {

	    	if(c1>c2)

	    	{

	    		while(s.charAt(r)!=')' && l<=r)

	    		{

	    			r--;

	    		}

	    		x2.add(r);

	    		r--;

	    		c2++;

	    	}

	    	else if(c2>c1)

	    	{

	    		while(s.charAt(l)!='(' && l<=r)

	    		{

	    			l++;

	    		}

	    		x1.add(l);

	    		l++;

	    		c1++;

	    	}

	    	else

	    	{

	    		while(l<=r && c1==c2)

	    		{

	    			if(s.charAt(l)=='(' && l<=r)

	    			{

	    				c1++;

	    				x1.add(l);

	    				l++;

	    			}

	    			else if(s.charAt(r)==')' && l<=r)

	    			{

	    				c2++;

	    				x2.add(r);

	    				r--;

	    			}

	    			else

	    			{

	    				l++;

	    				r--;

	    			}

	    		}

	    	}

	    }

	    if(!x1.isEmpty() && !x2.isEmpty())

	    {

		    Collections.sort(x1);

		   	Collections.sort(x2);

		    while((long)x1.get(x1.size()-1)>(long)x2.get(0))

		    {

		    	x1.remove(x1.size()-1);

		    	x2.remove(0);

		    }

		    while(x1.get(0)<0)

		    {

		    	x1.remove(0);

		    }

	    	while(x1.size()>=1 && x2.size()>=1 &&(long)x1.get(x1.size()-1)==(long)x2.get(0))

	    	{

	    		x1.remove(x1.size()-1);

	    		x2.remove(0);

	    	}

		   	int k1=x1.size(),k2=x2.size();

		   	while(x1.size()>Math.min(k1,k2))

		   	{

		   		x1.remove(x1.size()-1);

		   	}

	    	while(x2.size()>Math.min(k1,k2))

	    	{

	    		x2.remove(0);

		    }

	    }

	    if(x1.isEmpty() || x2.isEmpty())

	    {

	    	out.println(0);

	    }

	    else

	    {

		   	out.println(1);

		   	out.println(x1.size()+x2.size());

		   	for(int i=0;i<x1.size();i++)

		   	{

	    		out.print((x1.get(i)+1)+" ");

	    	}

		   	for(int i=0;i<x2.size();i++)

		    {

		   		out.print((x2.get(i)+1)+" ");

		   	}

	    }

	    out.close();

	}

}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

import java.io.*;

import java.util.*;

public class f{

    static int N, M, d[][], be[][], u[], v[];

    static ArrayList<Integer> graph[];

    static q qs[];

    static void dfs(int s, int id, int p, int di){

        d[s][id] = p;

        for(int i : graph[id]){

            if(i == p) continue;

            dfs(s, i, id, di+1);

        }

    }

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

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

        PrintWriter moo = new PrintWriter(System.out);

        N = Integer.parseInt(eat.readLine());

        graph = new ArrayList[N];

        for(int i = 0; i < N; i++) graph[i] = new ArrayList<Integer>();

        u = new int[N-1];

        v = new int[N-1];

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

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

            int x = Integer.parseInt(st.nextToken()) - 1, y = Integer.parseInt(st.nextToken()) - 1;

            u[i] = x;

            v[i] = y;

            graph[x].add(y);

            graph[y].add(x);

        }

        d = new int[N][N];

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

            dfs(i, i, -1, 0);

        }

        M = Integer.parseInt(eat.readLine());

        qs = new q[M];

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

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

            int a = Integer.parseInt(st.nextToken()) - 1, b = Integer.parseInt(st.nextToken()) - 1, g = Integer.parseInt(st.nextToken());

            qs[i] = new q(a, b, g);

        }

        Arrays.sort(qs);

        be = new int[N][N];

        boolean f = false;

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

            int a = qs[i].a, b = qs[i].b, g = qs[i].g;

            f = false;

            while(a != b){

                int nxt = d[b][a];

                if(be[a][nxt] <= g){

                    f = true;

                    be[a][nxt] = be[nxt][a] = g;

                }

                a = nxt;

            }

            if(!f){

                break;

            }

        }

        if(f){

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

                int x = be[u[i]][v[i]];

                moo.print((x == 0 ? 1 : x) + " ");

            }

            moo.println();

        }else{

            moo.println(-1);

        }

        eat.close(); moo.close();

    }

    static class q implements Comparable<q>{

        int a, b, g;

        q(int a, int b, int g){

            this.a = a;

            this.b = b;

            this.g = g;

        }

        public int compareTo(q x){

            return x.g - this.g;

        }

    }

}


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

import java.util.*;

import java.io.*;

// -------------------------Main class-------------------------

public class Main

{

    // private final int V;

    // private final List<List<Integer>> adj;

    // public Main(int V)

    // {

    //     this.V=V;

    //     adj=new ArrayList<>(V);

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

    //     adj.add(new LinkedList<>());

    // }

    // private void addEdge(int src, int dest)

    // {

    //     adj.get(src).add(dest);

    // }

    // private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack)

    // {

    //     if(recStack[i])

    //     return true;

    //     if(visited[i])

    //     return false;

    //     visited[i]=true;

    //     recStack[i]=true;

    //     List<Integer> children=adj.get(i);

    //     for(Integer c: children)

    //     {

    //         if(isCyclicUtil(c,visited,recStack))

    //         return true;

    //     }

    //     recStack[i]=false;

    //     return false;

    // }

    // private boolean isCyclic()

    // {

    //     boolean[] visited=new boolean[V];

    //     boolean[] recStack=new boolean[V];

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

    //     {

    //         if(isCyclicUtil(i, visited, recStack))

    //         return true;

    //     }

    //     return false;

    // }

    static long MOD=1000000007;

    static long power(long x, long y, long p)

	{

		// Initialize result

		long res = 1;

		// Update x if it is more than or

		// equal to p

		x = x % p;

		while (y > 0) {

			// If y is odd, multiply x

			// with result

			if (y % 2 == 1)

				res = (res * x) % p;

			// y must be even now

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

			x = (x * x) % p;

		}

		return res;

	}

	// Returns n^(-1) mod p

	static long modInverse(long n, long p)

	{

		return power(n, p - 2, p);

	}

	// Returns nCr % p using Fermat's

	// little theorem.

	static long nCrModPFermat(long n, long r,

							long p,long[] fac)

	{

		if (n<r)

			return 0;

	// Base case

		if (r == 0)

			return 1;

		return (fac[(int)n] * modInverse(fac[(int)r], p)

				% p * modInverse(fac[(int)n -(int) r], p)

				% p)

			% p;

	}

    // -------------------------Main function-------------------------

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

    {

        FastReader sc=new FastReader();

        PrintWriter pw=new PrintWriter(System.out);

        int t=1;

        // int x=10000;

        // int spf[]=new int[x+1];

        // spf[1]=1;

        // for(int j=2;j<=x;j++)

        // spf[j]=j;

        // for(int j=4;j<=x;j+=2)

        // spf[j]=2;

        // for(long j=3;(long)j*(long)j<(long)x;j++)

        // {

        //     if(spf[(int)j]==j)

        //     {

        //         for(long k=j*j;k<(long)x;k+=j)

        //         {

        //             if(spf[(int)k]==k)

        //             spf[(int)k]=(int)j;

        //         }

        //     }

        // }

        // long[] fac=new long[200001];

        // fac[0]=1;

        // for(int i=1;i<=200000;i++)

        // fac[i]=fac[i-1]*i%MOD;

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

        {

            long x=sc.nextLong();

            ArrayList<Long> factors=getFactors(x);

            factors.add(0,1L);

            factors.add(x);

            long ans1=1;

            long ans2=x;

            for(int j=0;j<factors.size();j++)

            {

                long temp1=factors.get(j);

                long temp2=x/temp1;

                if(lcm(temp1,temp2)==x&&Math.max(temp1,temp2)<=Math.max(ans1,ans2))

                {

                    ans1=temp1;

                    ans2=temp2;

                }

            }

            pw.write(ans1+" "+ans2+"\n");

        }

        pw.flush();

        pw.close();

    }

    // -------------------------Other functions-------------------------

    // Time Complexity : log(n)

    static long fast_power_mod(long n, long mod)

    {

        long pow2=2;

        long res=1;

        while(n>0)

        {

            if(n%2==1)

            res=(res%mod*pow2%mod)%mod;

            pow2=(pow2%mod*pow2%mod)%mod;

            n>>=1;

        }

        return res;

    }

    // Time Complexity : n*r

    static long nCrModpDP(long n, long r, long p)

    {

        long c[]=new long[(int)r+1];

        c[0]=1;

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

        {

            for(long k=Math.min(j,r);k>0;k--)

            c[(int)k]=(c[(int)k]%p+c[(int)k-1]%p)%p;

        }

        return c[(int)r];

    }

    // Time Complexity : log(n)

    static long nCrModpLucas(long n, long r, long p)

    {

        if(r==0)

        return 1;

        long ni=n%p;

        long ri=r%p;

        return (nCrModpLucas(n/p, r/p, p)%p*nCrModpDP(ni, ri, p)%p)%p;

    }

    // Time Complexity : log(mod)

    static long inverseMOD(long x, long mod) {

        if(mod==0)

        return 1;

        if(mod%2==1)

        return(x*inverseMOD(x, mod - 1))%MOD;

        else

        return inverseMOD((x * x) % MOD, mod/2);

    }

    // Time Complexity : log(max(a,b))

    static long bitwiseAND(long a, long b)

    {

        long shiftcount=0;

        while(a!=b&&a>0)

        {

            shiftcount++;

            a=a>>1;

            b=b>>1;

        }

        return (long)(a<<shiftcount);

    }

    // Time Complexity : n*m

    static void dfs(int j, ArrayList<ArrayList<Integer>> al, boolean[] visited)

    {

        visited[j]=true;

        for(int x=0;x<al.get(j).size();x++)

        {

            if(!visited[al.get(j).get(x)])

            dfs(al.get(j).get(x),al,visited);

        }

    }

    // Time Complexity : log(n) for composite numbers, n for prime numbers

    static long getPrimeFactors(long n)

    {

        int x=2;

        long count=0;

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

        while(n>1)

        {

            if(n%x==0)

            {

                // if(!al.contains(x))

                // al.add(x);

                count++;

                n/=x;

            }

            else

            x++;

        }

        return count;

    }

    // Time Complexity : log(n)

    static ArrayList<Integer> primeFactorization(int x, int[] spf)

    {

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

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

        while(x!=1)

        {

            if(!al.contains(spf[x]))

            al.add(spf[x]);

            map.put(spf[x],map.getOrDefault(spf[x],0)+1);

            x/=spf[x];

        }

        return al;

        // return map;

    }

    // Time Complexity : n*10

    static int[][] getBitMap(int[] a)

    {

        int n=a.length;

        int[][] bit_map=new int[n][32];

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

        Arrays.fill(bit_map[j],0);

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

        {

            int counter=0;

            while(a[j]!=0)

            {

                bit_map[j][counter]=a[j]%2;

                a[j]/=2;

                counter++;

            }

        }

        return bit_map;

    }

    // Time Complexity : n*log(log(n))

    static ArrayList<Integer> sieveOfEratosthenes(int n)

    {

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

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

        prime[j]=true;

        for(long p=2;p*p<=n;p++)

        {

            if(prime[(int)p])

            {

                for(long j=p*p;j<=n;j+=p)

                prime[(int)j]=false;

            }

        }

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

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

        {

            if(prime[(int)j])

            al.add((int)j);

        }

        return al;

    }

    // Time Complexity : n

    static boolean sortedIncreasing(int[] a)

    {

        int f=0;

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

        {

            if(a[j]<a[j-1])

            f=1;

        }

        return f==0?true:false;

    }

    // Time Complexity : n

    static boolean sortedDecreasing(int[] a)

    {

        int f=0;

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

        {

            if(a[j]>a[j-1])

            f=1;

        }

        return f==0?true:false;

    }

    // Time Complexity : sqrt(n)

    static ArrayList<Long> getFactors(long n)

    {

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

        // int count=0;

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

        {

            if(n%i==0)

            {

                al.add(i);

                // count++;

                if(n/i!=i)

                {

                    al.add(n/i);

                    // count++;

                }

            }

        }

        return al;

        // return count;

    }

    // Time Complexity : n*log(n)

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

    }

    // Time Complexity : n*log(n)

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

    }

    // Time Complexity : log(min(a,b))

    static long gcd(long a, long b)

    {

		return b==0?a:gcd(b,a%b);

	}

    // Time Complexity : log(min(a,b))

    static long lcm(long a, long b)

    {

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

    }

    // Time Complexity : log(n)

    static long floorSqrt(long x)

    {

        if(x==0||x==1)

        return x;

        long l=1;

        long r=(long)Math.sqrt(x)+1;

        long ans=0;

        while(l<=r)

        {

            long mid=l+(r-l)/2;

            long curr=mid*mid;

            if(curr==x)

            return mid;

            else if(curr>0&&curr<=x)

            {

                ans=mid;

                l=mid+1;

            }

            else

            r=mid-1;

        }

        return ans;

    }

    // Time Complexity : log(n*logn)

    static long getRemainderSum(long[] a, long totalsum, int x)

    {

        long k=0;

        outer :

        for(int mul=x;;mul+=x)

        {

            int l=0;

            int r=a.length-1;

            int index=-1;

            while(l<=r)

            {

                int mid=l+(r-l)/2;

                if(a[mid]>=mul)

                {

                    index=mid;

                    r=mid-1;

                }

                else

                l=mid+1;

            }

            if(index==-1)

            break outer;

            else

            k+=a.length-index;

        }

        return (totalsum-k*x);

    }

    // -------------------------Input class-------------------------

    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;

        }

    }

}

// -------------------------Other classes-------------------------

class Pair

{

    int first=0;

    int second=0;

    char ch='a';

    int index=-1;

    Pair(int x, int y)

    {

        first=x;

        second=y;

    }

    Pair(char x, int y)

    {

        ch=x;

        index=y;

    }

}

class NewComparator implements Comparator<Pair>

{

    public int compare(Pair p1, Pair p2)

    {

        return Long.compare(p2.second, p1.second);

    }

}


B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.

import java.io.*;

import java.util.StringTokenizer;

import static java.lang.Double.parseDouble;

import static java.lang.Integer.parseInt;

import static java.lang.Long.parseLong;

import static java.lang.System.in;

import static java.lang.System.out;

public class National_Project {

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

            int test = in.nextInt();

            while (test > 0) {

                //Your Code Here

                int length = in.nextInt();

                int good = in.nextInt();

                int bad = in.nextInt();

                calc(length, good, bad);

                test--;

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

    private static void calc(int length, int good_duration, int bad_duration) {

        long required = (length + 1) / 2;

        long good = good_duration;

        long ans = 0;

        //long good_count=0;

        if (length < good_duration) {

            ans = length;

        } else {

            ans += (required/good_duration)*(good_duration+bad_duration);

            if(required%good_duration==0)

            {

                ans-=bad_duration;

            }

            else

            {

                ans+=(required%good_duration);

            }

        }

        out.println(Math.max(ans,length));

    }

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

        if (a == 0) {

            return b;

        } else {

            return (gcd(b % a, a));

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

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

        }

        public void print(Object object) throws IOException {

            bw.append("" + object);

        }

        public void println(Object object) throws IOException {

            print(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

    public static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(new InputStreamReader(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 parseInt(next());

        }

        long nextLong() {

            return parseLong(next());

        }

        double nextDouble() {

            return parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine().trim();

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened;  The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.

import java.math.BigInteger;

import java.util.*;

import static java.lang.Math.*;

public class Main{

    public static void main(String args[]){

        Scanner sc=new Scanner(System.in);

        int testcase=sc.nextInt();

        for(int tc=1;tc<=testcase;tc++){

          //System.out.print("Case #"+tc+": ");

          int n = sc.nextInt();

          int a[] = new int[n];

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

            a[i] = sc.nextInt();

          }

          int k = 0;

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

            if(a[i] < i){

              break;

            }

            k = i;

          }

          boolean flag = true;

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

            if(a[i] < n-1-i){

              flag = false;

              break;

            }

          }

          if(flag)

            System.out.println("Yes");

          else

            System.out.println("No");

        }

        sc.close();

    }

    static long fact(long n)

    {

    // single line to find factorial

    return (n == 1 || n == 0) ? 1 : n * fact(n - 1);

    }

    static boolean isSorted(int a[]){

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

        if(a[i] < a[i-1])

          return false;

      }

      return true;

    }

    static int gcd(int a, int b)

    {

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    static int lcm(int a, int b)

    {

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

    }

    static int upper_bound(int[] arr, int key, int i)

    {

      if(Arrays.binarySearch(arr, key) >= 0)

        return Arrays.binarySearch(arr, key);

      int mid, N = arr.length;

        // Initialise starting index and

        // ending index

        int low = 0;

        int high = i;

        // Till low is less than high

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

            // Find the index of the middle element

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

            // If key is greater than or equal

            // to arr[mid], then find in

            // right subarray

            if (key >= arr[mid]) {

                low = mid + 1;

            }

            // If key is less than arr[mid]

            // then find in left subarray

            else {

                high = mid;

            }

        }

        return low;

    }

    static int lower_bound(int[] arr, int key, int i)

    {

      if(Arrays.binarySearch(arr, key) >= 0)

      return Arrays.binarySearch(arr, key);

        // Initialize starting index and

        // ending index

        int low = 0, high = i;

        int mid;

        // Till high does not crosses low

        while (low < high) {

            // Find the index of the middle element

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

            // If key is less than or equal

            // to array[mid], then find in

            // left subarray

            if (key <= arr[mid]) {

                high = mid;

            }

            // If key is greater than array[mid],

            // then find in right subarray

            else {

                low = mid + 1;

            }

        }

        return low;

    }

    static boolean palin(int arr[], int i, int j){

      while(i < j){

        if(arr[i] != arr[j])

          return false;

        i++;

        j--;

      }

      return true;

    }

    static boolean palin(String s){

      int i=0,j=s.length()-1;

      while(i<j){

        if(s.charAt(i)!=s.charAt(j))

          return false;

        i++;

        j--;

      }

      return true;

    }

    static long minSum(int arr[], int n, int k)

    {

        // k must be smaller than n

        if (n < k)

        {

          // System.out.println("Invalid");

           return -1;

        }

        // Compute sum of first window of size k

        long res = 0;

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

           res += arr[i];

        // Compute sums of remaining windows by

        // removing first element of previous

        // window and adding last element of

        // current window.

        long curr_sum = res;

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

        {

           curr_sum += arr[i] - arr[i-k];

           res = Math.min(res, curr_sum);

        }

        return res;

    }

    static int nextIndex(int a[], int x){

      int n=a.length;

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

        if(a[i]>a[i+1]){

          return i;

        }

      }

      return n;

    }

    static void rev(int a[], int i, int j){

      while(i<j){

        int t=a[i];

        a[i]=a[j];

        a[j]=t;

        i++;

        j--;

      }

    }

    static int sorted(int arr[], int n)

    {

        // Array has one or no element or the

        // rest are already checked and approved.

        if (n == 1 || n == 0)

            return 1;

        // Unsorted pair found (Equal values allowed)

        if (arr[n - 1] < arr[n - 2])

            return 0;

        // Last pair was sorted

        // Keep on checking

        return sorted(arr, n - 1);

    }

    static void sieveOfEratosthenes(int n, int a[])

    {

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

        a[i]=1;

      }

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

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

          a[j]=0;

        }

      }

    }

    static boolean isPowerOfTwo(int n)

    {

        return (int)(Math.ceil((Math.log(n) / Math.log(2))))

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

    }

    static int countBits(int number)

    {

        // log function in base 2

        // take only integer part

        return (int)(Math.log(number) /

                     Math.log(2) + 1);

    }

    public static void swap(int ans[], int i, int j) {

        int temp=ans[i];

        ans[i]=ans[j];

        ans[j]=temp;

    }

    static int power(int x, int y, int p)

  {

    int res = 1; // Initialize result

    x = x % p; // Update x if it is more than or

    // equal to p

    if (x == 0)

      return 0; // In case x is divisible by p;

    while (y > 0)

    {

      // If y is odd, multiply x with result

      if ((y & 1) != 0)

        res = (res * x) % p;

      // y must be even now

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

      x = (x * x) % p;

    }

    return res;

  }

}


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

import java.io.*;

import java.util.*;

public class Main {

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

        //BufferedReader f = new BufferedReader(new FileReader("uva.in"));

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

        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

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

        while(t-- > 0) {

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

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

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

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

            int ans = 30000;

            int resA = 0;

            int resB = 0;

            int resC = 0;

            for(int A = 1; A <= 10000; A++) {

                for(int B = A; B <= 20000; B += A) {

                    int C1 = c/B*B;

                    int C2 = (c+B-1)/B*B;

                    int temp = Math.abs(A-a)+Math.abs(B-b)+Math.abs(C2-c);

                    if(temp < ans) {

                        ans = temp;

                        resA = A;

                        resB = B;

                        resC = C2;

                    }

                    if(C1 > 0) {

                        temp = Math.abs(A-a)+Math.abs(B-b)+Math.abs(C1-c);

                        if(temp < ans) {

                            ans = temp;

                            resA = A;

                            resB = B;

                            resC = C1;

                        }

                    }

                }

            }

            out.println(ans);

            out.println(resA + " " + resB + " " + resC);

        }

        f.close();

        out.close();

    }

}


B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs:  buy one bus ticket to get from 11 to 33,  buy one tram ticket to get from 33 to 66,  buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6

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

import static java.lang.Math.*;
import static java.util.Arrays.sort;

public class Codeforces {
	// static int mod = 998244353;
	static int mod = 1000000007;

	public static void main(String[] args) {
		FastReader fastReader = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		int t = fastReader.nextInt();
		while (t-- > 0) {
			int a = fastReader.nextInt();
			int b = fastReader.nextInt();
			int q = fastReader.nextInt();
			char c[] = fastReader.nextLine().toCharArray();
			int n = c.length;
			int index = n - 1;
			for (int i = n - 2; i >= 0; i--) {
				if (c[i] == 'B') {
					q -= b;
				} else {
					q -= a;
				}
				int cur_indx = i - 1;
				while (cur_indx >= 0 && c[cur_indx] == c[i])
					cur_indx--;
				if (q >= 0) {
					index = (cur_indx + 1);
				} else {
					break;
				}
				i = cur_indx + 1;
			}
			out.println((index + 1));
		}
		out.close();
	}

	// constants
	static final int IBIG = 1000000007;
	static final int IMAX = 2147483647;
	static final long LMAX = 9223372036854775807L;
	static Random __r = new Random();

	// math util
	static int minof(int a, int b, int c) {
		return min(a, min(b, c));
	}

	static int minof(int... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return min(x[0], x[1]);
		if (x.length == 3)
			return min(x[0], min(x[1], x[2]));
		int min = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] < min)
				min = x[i];
		return min;
	}

	static long minof(long a, long b, long c) {
		return min(a, min(b, c));
	}

	static long minof(long... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return min(x[0], x[1]);
		if (x.length == 3)
			return min(x[0], min(x[1], x[2]));
		long min = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] < min)
				min = x[i];
		return min;
	}

	static int maxof(int a, int b, int c) {
		return max(a, max(b, c));
	}

	static int maxof(int... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return max(x[0], x[1]);
		if (x.length == 3)
			return max(x[0], max(x[1], x[2]));
		int max = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] > max)
				max = x[i];
		return max;
	}

	static long maxof(long a, long b, long c) {
		return max(a, max(b, c));
	}

	static long maxof(long... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return max(x[0], x[1]);
		if (x.length == 3)
			return max(x[0], max(x[1], x[2]));
		long max = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] > max)
				max = x[i];
		return max;
	}

	static int powi(int a, int b) {
		if (a == 0)
			return 0;
		int ans = 1;
		while (b > 0) {
			if ((b & 1) > 0)
				ans *= a;
			a *= a;
			b >>= 1;
		}
		return ans;
	}

	static long powl(long a, int b) {
		if (a == 0)
			return 0;
		long ans = 1;
		while (b > 0) {
			if ((b & 1) > 0)
				ans *= a;
			a *= a;
			b >>= 1;
		}
		return ans;
	}

	static int fli(double d) {
		return (int) d;
	}

	static int cei(double d) {
		return (int) ceil(d);
	}

	static long fll(double d) {
		return (long) d;
	}

	static long cel(double d) {
		return (long) ceil(d);
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	static int lcm(int a, int b) {
		return (a / gcd(a, b)) * b;
	}

	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	static long lcm(long a, long b) {
		return (a / gcd(a, b)) * b;
	}

	static int[] exgcd(int a, int b) {
		if (b == 0)
			return new int[] { 1, 0 };
		int[] y = exgcd(b, a % b);
		return new int[] { y[1], y[0] - y[1] * (a / b) };
	}

	static long[] exgcd(long a, long b) {
		if (b == 0)
			return new long[] { 1, 0 };
		long[] y = exgcd(b, a % b);
		return new long[] { y[1], y[0] - y[1] * (a / b) };
	}

	static int randInt(int min, int max) {
		return __r.nextInt(max - min + 1) + min;
	}

	static long mix(long x) {
		x += 0x9e3779b97f4a7c15L;
		x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
		x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
		return x ^ (x >> 31);
	}

	public static boolean[] findPrimes(int limit) {
		assert limit >= 2;

		final boolean[] nonPrimes = new boolean[limit];
		nonPrimes[0] = true;
		nonPrimes[1] = true;

		int sqrt = (int) Math.sqrt(limit);
		for (int i = 2; i <= sqrt; i++) {
			if (nonPrimes[i])
				continue;
			for (int j = i; j < limit; j += i) {
				if (!nonPrimes[j] && i != j)
					nonPrimes[j] = true;
			}
		}

		return nonPrimes;
	}

	// array util
	static void reverse(int[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			int swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(long[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			long swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(double[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			double swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(char[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			char swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void shuffle(int[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			int swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void shuffle(long[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			long swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void shuffle(double[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			double swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void rsort(int[] a) {
		shuffle(a);
		sort(a);
	}

	static void rsort(long[] a) {
		shuffle(a);
		sort(a);
	}

	static void rsort(double[] a) {
		shuffle(a);
		sort(a);
	}

	static int[] copy(int[] a) {
		int[] ans = new int[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static long[] copy(long[] a) {
		long[] ans = new long[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static double[] copy(double[] a) {
		double[] ans = new double[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static char[] copy(char[] a) {
		char[] ans = new char[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static class FastReader {

		BufferedReader br;
		StringTokenizer st;

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

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

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

		int[] ria(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = Integer.parseInt(next());
			return a;
		}

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

		long[] rla(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = Long.parseLong(next());
			return a;
		}

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

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


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import java.util.*;

import java.io.*;

public class Main{

    static  class pair{

        long x ;long y ;

        pair(long x ,long y )

        {

            this.x=x;

            this.y =y;

        }

    }

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

    }

    //dsu

    static int[] parent,rank;

    public static void dsu(int n){

        parent = new int[n]; rank = new int[n];

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

            parent[i]=i; rank[i]=1;

        }

    }

    public static int find(int i){

        if(i==parent[i] ) return i;

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

    }

    static int f(int arr[],int i )

    {

        if(i==arr[i])

            return i ;

        return arr[i]=f(arr,arr[i]);

    }

    public static void merge(int i, int j){

        i=find(i);

        j=find(j);

        if(rank[i]>=rank[j]){

            rank[i]+=rank[j];

            parent[j]=i;

        }

        else {

            rank[j]+=rank[i];

            parent[i]=j;

        }

    }

    public static int help(boolean[] v){

        HashSet<Integer> s = new HashSet<>();

        for(int e=1;e<v.length;e++){

            int i=find(e);

            if(v[i]) s.add(i);

        }

        //    System.out.print(Arrays.toString(parent));

        return s.size();

    }

    static int  help(int[][] arr, int i, int n, int[] heigh) {

        if(arr[i][0]==-1&&arr[i][1]==-1)

            return 0;

        if(arr[i][0]==-1)

        {

            return heigh[arr[i][1]]-1;

        }

        else if(arr[i][1]==-1)

            return heigh[arr[i][0]]-1;

        else

        {

            int op1 =heigh[arr[i][1]]-1+help(arr, arr[i][0], n, heigh);

            int op2 =heigh[arr[i][0]]-1+help(arr, arr[i][1], n, heigh);

            return Math.max(op1,op2);

        }

    }

    static int heights(int arr[][], int i , int heig[])

    {

        if(arr[i][0]==-1&&arr[i][1]==-1)

            return 0;

        if(heig[i]!=-1)

            return heig[i];

        if(arr[i][0]==-1)

            return heig[i]=1+heights(arr,arr[i][1],heig);

        if(arr[i][1]==-1)

            return  heig[i]=1+heights(arr,arr[i][0],heig);

        else return heig[i]= 1+heights(arr,arr[i][1],heig)+heights(arr,arr[i][0],heig);

    }

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

            long testCases =in.nextLong();

            fl:

            while (testCases-- > 0) {

long n =in.nextLong();

long arr[]=new long[(int) n];

long sum =0;

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

    arr[i] = in.nextLong();

    sum=sum+arr[i];

}long curr=0;

long max =0;

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

{

    curr=curr+arr[i];

    if(curr<0)

        curr=0;

    max=Math.max(curr,max);

}curr=0;

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

                {

                    curr=curr+arr[i];

                    if(curr<0)

                        curr=0;

                    max=Math.max(curr,max);

                }

if(max<sum)

                System.out.println("Yes");

else

    System.out.println("No");

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

import java.io.*;

import java.util.*;

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1322c {

    static int par[];

    static int find(int i) {

        return i == par[i] ? i : (par[i] = find(par[i]));

    }

    static void union(int i, int j) {

        int a = find(i), b = find(j);

        if(a != b) {

            par[b] = a;

        }

    }

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

        int t = ri();

        while(t --> 0) {

            int n = rni(), m = ni();

            par = new int[n];

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

                par[i] = i;

            }

            long c[] = rla(n);

            List<Set<Integer>> g = sgraph(2 * n);

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

                int u = rni() - 1, v = ni() + n - 1;

                connect(g, u, v);

            }

            if(m == 0) {

                prln(0);

            } else {

                Map<Long, Long> sum = new HashMap<>();

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

                    long hash = 0;

                    for(int j : g.get(n + i)) {

                        hash ^= hash(j);

                    }

                    sum.put(hash, sum.getOrDefault(hash, 0L) + c[i]);

                }

                long ans = 0;

                for(long k : sum.keySet()) {

                    if(k != 0) {

                        if(ans == 0) {

                            ans = sum.get(k);

                        } else {

                            ans = gcf(ans, sum.get(k));

                        }

                    }

                }

                prln(ans);

            }

            if(t > 0) {

                rline();

            }

        }

        close();

    }

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

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

    static StringTokenizer input;

    static Random rand = new Random();

    // references

    // IBIG = 1e9 + 7

    // IMAX ~= 2e10

    // LMAX ~= 9e18

    // constants

    static final int IBIG = 1000000007;

    static final int IMAX = 2147483647;

    static final int IMIN = -2147483648;

    static final long LMAX = 9223372036854775807L;

    static final long LMIN = -9223372036854775808L;

    // math util

    static int minof(int a, int b, int c) {return min(a, min(b, c));}

    static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}

    static long minof(long a, long b, long c) {return min(a, min(b, c));}

    static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}

    static int maxof(int a, int b, int c) {return max(a, max(b, c));}

    static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}

    static long maxof(long a, long b, long c) {return max(a, max(b, c));}

    static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}

    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static int fli(double d) {return (int)d;}

    static int cei(double d) {return (int)ceil(d);}

    static long fll(double d) {return (long)d;}

    static long cel(double d) {return (long)ceil(d);}

    static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}

    static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}

    static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}

    static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}

    // array util

    static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void rsort(int[] a) {shuffle(a); sort(a);}

    static void rsort(long[] a) {shuffle(a); sort(a);}

    static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}

    static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}

    static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}

    static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}

    static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}

    // graph util

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

    static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}

    static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);}

    static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}

    static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);}

    static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}

    static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}

    static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}

    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}

    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}

    static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}

    static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}

    static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}

    static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}

    // input

    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}

    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}

    static long rl() throws IOException {return Long.parseLong(__in.readLine());}

    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}

    static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}

    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}

    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}

    static String rline() throws IOException {return __in.readLine();}

    static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}

    static int ni() {return Integer.parseInt(input.nextToken());}

    static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}

    static long nl() {return Long.parseLong(input.nextToken());}

    // output

    static void pr(int i) {__out.print(i);}

    static void prln(int i) {__out.println(i);}

    static void pr(long l) {__out.print(l);}

    static void prln(long l) {__out.println(l);}

    static void pr(double d) {__out.print(d);}

    static void prln(double d) {__out.println(d);}

    static void pr(char c) {__out.print(c);}

    static void prln(char c) {__out.println(c);}

    static void pr(char[] s) {__out.print(new String(s));}

    static void prln(char[] s) {__out.println(new String(s));}

    static void pr(String s) {__out.print(s);}

    static void prln(String s) {__out.println(s);}

    static void pr(Object o) {__out.print(o);}

    static void prln(Object o) {__out.println(o);}

    static void prln() {__out.println();}

    static void pryes() {__out.println("yes");}

    static void pry() {__out.println("Yes");}

    static void prY() {__out.println("YES");}

    static void prno() {__out.println("no");}

    static void prn() {__out.println("No");}

    static void prN() {__out.println("NO");}

    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};

    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}

    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}

    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}

    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}

    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}

    static void h() {__out.println("hlfd");}

    static void flush() {__out.flush();}

    static void close() {__out.close();}

}