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

}


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

//package com.example.practice.codeforces.sc2500;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
//D. Happy New Year
public class Solution1 {
    public static void main (String [] args) throws IOException {
        // Use BufferedReader rather than RandomAccessFile; it's much faster
        final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        // input file name goes above
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));

        StringTokenizer st = new StringTokenizer(input.readLine());
        int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        int[][] ns = new int[n][2];
        for(int i=0;i<n;++i){
            st = new StringTokenizer(input.readLine());
            ns[i][0] = Integer.parseInt(st.nextToken());
            ns[i][1] = Integer.parseInt(st.nextToken());
        }
        System.out.println(calc(n, m, k, ns));
        //out.close();       // close the output file
    }

    private static int calc(final int n, final int m, final int k, int[][] ns) {
        HashMap<Integer, Node> map = new HashMap<>();
        int p = 0, pre = 0, finished = 0;
        for (int[] kk : ns){
            if (!map.containsKey(kk[0])){
                map.put(kk[0], new Node(kk[0]));
            }
            map.get(kk[0]).st.add(p);
            if (!map.containsKey(kk[1]+1)){
                map.put(kk[1]+1, new Node(kk[1]+1));
            }
            map.get(kk[1]+1).en.add(p++);
        }
        Node[] nds = new Node[map.size()];
        p = 0;
        for (Node nd : map.values()){
            nds[p++] = nd;
        }
        Arrays.sort(nds);
        final int ks = 1<<k;
        int[][] dp = new int[nds.length][ks];
        int[] mask = new int[n], bitCount = new int[ks];
        for (int i=1;i<ks;++i){
            if((i&1) == 1)bitCount[i]=bitCount[i-1]+1;
            else bitCount[i]=bitCount[i>>1];
        }
        for (int i=0;i<dp.length-1;++i){
            pre -= finished;
            int d = 1, added = 0;
            for (int a : nds[i].st){
                while((d&pre) != 0) {
                    d = d << 1;
                }
                mask[a] = d;
                added += d;
                pre += d;
            }
            finished = 0;
            for (int a : nds[i+1].en){
                finished += mask[a];
            }
            for (int j=0;j<ks;++j) {
                if ((j & pre) == j) {
                    int t = 0;
                    if ((bitCount[j] & 1) == 1) {
                        t += nds[i + 1].start - nds[i].start;
                    }
                    if (i > 0) {
                        t += dp[i - 1][j - (j & added)];
                    }
                    dp[i][j - (j & finished)] = Math.max(dp[i][j - (j & finished)], t);
                }
            }
        }
        return dp[dp.length-2][0];
    }

    static class Node implements Comparable<Node>{
        int start;
        ArrayList<Integer> st;
        ArrayList<Integer> en;
        public Node(int a){
            start = a;
            st = new ArrayList<>(4);
            en = new ArrayList<>(4);
        }
        @Override
        public int compareTo(Node nd){
            return this.start - nd.start;
        }
    }
}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

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.LinkedHashMap;

import java.util.Map;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.stream.Collectors;

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)

        {

        	long n=sc.nextLong();

			long s=sc.nextLong();

			long k=sc.nextLong();

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

			HashMap<Long,Boolean> x=new HashMap<Long,Boolean>();

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

			{

				x.put(sc.nextLong(),false);

			}

			long s1=s,s2=s;

			while(true)

			{

				if(!x.containsKey(s) && s<=n)

				{

					out.println(Math.abs(s2-s));

					break;

				}

				if(!x.containsKey(s1) && s1>=1)

				{

					out.println(Math.abs(s1-s2));

					break;

				}

				s++;

				s1--;

			}

        }

	    out.close();

	}

}


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

import java.io.* ;

public class Main

{

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

    {

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

        PrintWriter out =  new PrintWriter ( System.out );

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

        int[] arr = new int [ t ] ;

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

            arr[ i ] =Integer.parseInt( br.readLine() ) ;

        for( int item : arr )

            out.println( "1 " + ( item-1 ) );

        out.flush();

        return  ;

    }

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

import java.util.*;

public class Main

{

	public static void main(String[] args) {

		//System.out.println("Hello World");

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

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

		{

		    int a=sc.nextInt();

		    int b=sc.nextInt();

		    if(a==b)

		    {

		        System.out.println("0");

		    }

		    else if(a>b)

		    {

		        if((a-b)%2==0)

		        System.out.println("1");

		        else

		        System.out.println("2");

		    }

		    else

		    {

		        if((b-a)%2!=0)

		        System.out.println("1");

		        else

		        System.out.println("2");

		    }

		}

	}

}


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

import java.io.*;

import java.util.*;

public class Main {

    private static final InputReader in = new InputReader(System.in);

    private static final PrintWriter pw = new PrintWriter(System.out);

    public static void main(String[] args) {

        int n = in.nextInt();

        Integer[] d = new Integer[n];

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

            d[i] = in.nextInt();

        }

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

            d[i] -= in.nextInt();

        }

        Arrays.sort(d);

        long ans = 0;

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

            int l = i + 1, r = n - 1, x = n;

            while (l <= r) {

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

                if (d[mid] > -d[i]) {

                    r = mid - 1;

                    x = mid;

                }

                else l = mid + 1;

            }

            ans += n - x;

        }

        pw.println(ans);

        pw.close();

    }

    private static class Pair {

        private int first, second;

        public Pair(int first, int second) {

            this.first = first;

            this.second = second;

        }

    }

    private static class InputReader {

        public BufferedReader reader;

        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {

            reader = new BufferedReader(new InputStreamReader(stream), 32768);

            tokenizer = null;

        }

        public boolean ready() throws IOException {

            return reader.ready();

        }

        public String next() {

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

                try {

                    tokenizer = new StringTokenizer(reader.readLine());

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public String nextLine() {

            String str = null;

            try {

                str = reader.readLine();

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

            return str;

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

        public Double nextDouble() {

            return Double.parseDouble(next());

        }

    }

}


import java.io.*;

import java.util.*;

import java.math.*;

public class Main{

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

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

	private static InputStream inputstream = System.in;

	private static FastScanner in = new FastScanner(inputstream);

	public static void main(String[] args){

		Task solver = new Task();

		int TaskCase = in.nextInt();

		solver.solve(TaskCase);

		cout.flush();

	}

	private static class Task{

		long value[];

		int n,m;

		TreeMap<Integer,Long> mp = new TreeMap<>();

		public void solve(int T){

			while(T-->0){

				n = in.nextInt();

				m = in.nextInt();

				value = new long[n];

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

				if(n==1){

					in.nextInt();

					in.nextInt();

					cout.print(value[0]);

					cout.write('\n');

					continue;

				}

				ArrayList<Integer>[] G = Utils.ListArray(n);

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

					int u = in.nextInt() - 1, v = in.nextInt() - 1;

					G[v].add(u);

				}

				mp.clear();

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

					if(G[i].isEmpty()) continue;

					G[i].sort((x,y)->{ return x-y; });

					int hx = G[i].hashCode();

					if(!mp.containsKey(hx)) mp.put(hx,value[i]);

					else mp.put(hx,mp.get(hx)+value[i]);

				}

				Long ans = 0l;

				for(long v : mp.values()) ans = gcd(ans,v);

				cout.write(ans.toString()+'\n');

			}

		}

		private long gcd(long A, long B){

			return B!=0 ? gcd(B,A%B) : A;

		}

	}

	private static class Utils{

		public static <T> ArrayList<T>[] ListArray(int _size){

			ArrayList<T>[] ret = new ArrayList[_size];

			for(int i = 0; i < _size; i++) ret[i] = new ArrayList<>();

			return ret;

		}

	}

	public static class FastScanner {

		BufferedReader br;

		StringTokenizer st;

		public FastScanner(InputStream in) {

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

		}

		public int nextInt() {

			return Integer.parseInt(next());

		}

		public boolean hasMoreTokens() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

					return false;

				}

				if (line == null) {

					return false;

				}

				st = new StringTokenizer(line);

			}

			return true;

		}

		public String next() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

				}

				st = new StringTokenizer(line);

			}

			return st.nextToken();

		}

		public long nextLong() {

			return Long.parseLong(next());

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] ret = new int[n];

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

				ret[i] = nextInt();

			}

			return ret;

		}

		public long[] nextLongArray(int n) {

			long[] ret = new long[n];

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

				ret[i] = nextLong();

			}

			return ret;

		}

	}

}