import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class D_Fight_with_Monsters {

    static long mod = Long.MAX_VALUE;

    public static void main(String[] args) {

        OutputStream outputStream = System.out;

        PrintWriter out = new PrintWriter(outputStream);

        FastReader f = new FastReader();

        int t = 1;

        while(t-- > 0){

            solve(f, out);

        }

        out.close();

    }

    public static void solve(FastReader f, PrintWriter out) {

        int n = f.nextInt();

        long a = f.nextLong();

        long b = f.nextLong();

        long k = f.nextLong();

        long arr[] = f.nextArray(n);

        long used[] = new long[n];

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

            long rem = arr[i]%(a+b);

            if(rem == 0) {

                rem = a+b;

            }

            used[i] = (rem+a-1)/a - 1;

        }

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

        //     out.print(used[i] + " ");

        // }

        // out.println();

        sort(used);

        int point = 0;

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

            if(k-used[i] >= 0) {

                point++;

                k -= used[i];

            } else {

                break;

            }

        }

        out.println(point);

    }

    // Sort an array

    public static void sort(long arr[]) {

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

        for(long i: arr) {

            al.add(i);

        }

        Collections.sort(al);

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

            arr[i] = al.get(i);

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

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

            if(n%i == 0) {

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

                if(i != n/i) {

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

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

        if(n % 2 == 0 || n % 3 == 0) return false;

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

            if(n % i == 0 || n % (i+2) == 0) {

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

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

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

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

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

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

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

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

        long res = 1;

        while(b > 0) {

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

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

    public static long nCr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / (fact(r) * fact(n-r));

        return ans;

    }

    // Find nPr

    public static long nPr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / fact(r);

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

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

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        long[] nextArray(int n) {

            long[] a = new long[n];

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

                a[i] = nextLong();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */

// (a/b)%mod == (a * moduloInverse(b)) % mod;

// moduloInverse(b) = power(b, mod-2);


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

import java.io.*;

import java.util.*;

public class  Main{

	static class node implements Comparable<node>{

		int i,val;

		node(int ii,int v){

			i=ii;val=v;

		}

		@Override

		public int compareTo(node o) {

			if(val==o.val)return i-o.i;

			return val-o.val;

		}

		public String toString() {return i+" "+val;}

	}

	static LinkedList<Integer>children[];

	static int[]cnt;

	static boolean ok=true;

	static int[]empty=new int[1];

	static ArrayList<node> dfs(int i) {

		if(!ok) {

			return new ArrayList<node>();

		}

		if(children[i].size()==0) {

			if(cnt[i]>0) {

				ok=false;

				return new ArrayList<node>();

			}

			ArrayList<node>arr=new ArrayList<Main.node>();

			arr.add(new node(i, 1));

			return arr;

		}

		ArrayList<node>arr=new ArrayList<Main.node>();

		for(int j:children[i]) {

			ArrayList<node>child=dfs(j);

			for(node n:child) {

				arr.add(n);

			}

		}

		if(cnt[i]>arr.size()) {

			ok=false;

			return new ArrayList<node>();

		}

		Collections.sort(arr);

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

		int val;

		if(cnt[i]==0)val=1;

		else {

			val=arr.get(cnt[i]-1).val+1;

		}

		if(cnt[i]<arr.size() && arr.get(cnt[i]).val<=val) {

			int dif=val-arr.get(cnt[i]).val+1;

			for(int idx=cnt[i];idx<arr.size();idx++) {

					node cur=arr.get(idx);

					arr.set(idx, new node(cur.i, cur.val+dif));

			}

		}

		arr.add(new node(i, val));

		return arr;

	}

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

		MScanner sc=new MScanner(System.in);

		PrintWriter pw=new PrintWriter(System.out);

		int n=sc.nextInt();

		children=new LinkedList[n];

		cnt=new int[n];

		int root=-1;

		for(int i=0;i<n;i++)children[i]=new LinkedList<Integer>();

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

			int par=sc.nextInt()-1;cnt[i]=sc.nextInt();

			if(par!=-1) {

				children[par].add(i);

			}

			else {

				root=i;

			}

		}

		ArrayList<node>ans=dfs(root);

		//System.out.println(ans);

		if(!ok) {

			pw.println("NO");

			pw.flush();

			return;

		}

		pw.println("YES");

		int[]vals=new int[n];

		for(node x:ans) {

			vals[x.i]=x.val;

		}

		for(int i:vals)pw.println(i);

		pw.flush();

	}

	static class MScanner {

		StringTokenizer st;

		BufferedReader br;

		public MScanner(InputStream system) {

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

		}

		public MScanner(String file) throws Exception {

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

		}

		public String next() throws IOException {

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

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

			return st.nextToken();

		}

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

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

	        return in;

		}

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

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

	        return in;

		}

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

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

	        return in;

		}

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

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

	        return in;

		}

		public String nextLine() throws IOException {

			return br.readLine();

		}

		public int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		public double nextDouble() throws IOException {

			return Double.parseDouble(next());

		}

		public char nextChar() throws IOException {

			return next().charAt(0);

		}

		public Long nextLong() throws IOException {

			return Long.parseLong(next());

		}

		public boolean ready() throws IOException {

			return br.ready();

		}

		public void waitForInput() throws InterruptedException {

			Thread.sleep(3000);

		}

	}

}


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

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import static java.lang.System.out;

import java.util.*;

import java.io.*;

import java.math.*;

/*

-> Give your 100%, that's it!

-> Rule To Solve Any Problem:

    1. Read the problem.

    2. Think About It.

    3. Solve it!

*/

public class Template {

	static int mod = 1000000007;

	public static void main(String[] args){

        FastScanner sc = new FastScanner();

        PrintWriter out = new PrintWriter(System.out);

        int yo = sc.nextInt();

        while (yo-- > 0) {

            int a = sc.nextInt(), b = sc.nextInt();

            int x = sc.nextInt(), y = sc.nextInt();

            int up = x * b;

            int down =(a-x-1) * b;

            int left = a * y;

            int right = a * (b-y-1);

            out.println(max(max(up,down),max(left,right)));

        }

        out.close();

	}

    /*

    Source: hu_tao

         Random stuff to try when stuck:

            -if it's 2C then it's dp

            -for combo/probability problems, expand the given form we're interested in

            -make everything the same then build an answer (constructive, make everything 0 then do something)

            -something appears in parts of 2 --> model as graph

            -assume a greedy then try to show why it works

            -find way to simplify into one variable if multiple exist

            -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)

            -find lower and upper bounds on answer

            -figure out what ur trying to find and isolate it

            -see what observations you have and come up with more continuations

            -work backwards (in constructive, go from the goal to the start)

            -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)

            -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)

            -draw something

            -simulate a process

            -dont implement something unless if ur fairly confident its correct

            -after 3 bad submissions move on to next problem if applicable

            -do something instead of nothing and stay organized

            -write stuff down

         Random stuff to check when wa:

            -if code is way too long/cancer then reassess

            -switched N/M

            -int overflow

            -switched variables

            -wrong MOD

            -hardcoded edge case incorrectly

         Random stuff to check when tle:

            -continue instead of break

            -condition in for/while loop bad

         Random stuff to check when rte:

            -switched N/M

            -long to int/int overflow

            -division by 0

            -edge case for empty list/data structure/N=1

      */

	public static class Pair {

		int x;

		int y;

		public Pair(int x, int y) {

			this.x = x;

			this.y = y;

		}

	}

	public static void sort(int[] arr) {

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

		for (int x : arr)

			ls.add(x);

		Collections.sort(ls);

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

			arr[i] = ls.get(i);

	}

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

		if (b == 0)

			return a;

		return gcd(b, a % b);

	}

	static boolean[] sieve(int N) {

		boolean[] sieve = new boolean[N + 1];

		for (int i = 2; i <= N; i++)

			sieve[i] = true;

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

			if (sieve[i]) {

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

					sieve[j] = false;

				}

			}

		}

		return sieve;

	}

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

		long res = 1L;

		x = x % p;

		while (y > 0) {

			if ((y & 1) == 1)

				res = (res * x) % p;

			y >>= 1;

			x = (x * x) % p;

		}

		return res;

	}

	public static void print(int[] arr) {

		//for debugging only

		for (int x : arr)

			out.print(x + " ");

		out.println();

	}

	static class FastScanner {

		private int BS = 1 << 16;

		private char NC = (char) 0;

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

		private int bId = 0, size = 0;

		private char c = NC;

		private double cnt = 1;

		private BufferedInputStream in;

		public FastScanner() {

			in = new BufferedInputStream(System.in, BS);

		}

		public FastScanner(String s) {

			try {

				in = new BufferedInputStream(new FileInputStream(new File(s)), BS);

			} catch (Exception e) {

				in = new BufferedInputStream(System.in, BS);

			}

		}

		private char getChar() {

			while (bId == size) {

				try {

					size = in.read(buf);

				} catch (Exception e) {

					return NC;

				}

				if (size == -1)

					return NC;

				bId = 0;

			}

			return (char) buf[bId++];

		}

		public int nextInt() {

			return (int) nextLong();

		}

		public int[] readInts(int N) {

			int[] res = new int[N];

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

				res[i] = (int) nextLong();

			}

			return res;

		}

		public long[] readLongs(int N) {

			long[] res = new long[N];

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

				res[i] = nextLong();

			}

			return res;

		}

		public long nextLong() {

			cnt = 1;

			boolean neg = false;

			if (c == NC)

				c = getChar();

			for (; (c < '0' || c > '9'); c = getChar()) {

				if (c == '-')

					neg = true;

			}

			long res = 0;

			for (; c >= '0' && c <= '9'; c = getChar()) {

				res = (res << 3) + (res << 1) + c - '0';

				cnt *= 10;

			}

			return neg ? -res : res;

		}

		public double nextDouble() {

			double cur = nextLong();

			return c != '.' ? cur : cur + nextLong() / cnt;

		}

		public double[] readDoubles(int N) {

			double[] res = new double[N];

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

				res[i] = nextDouble();

			}

			return res;

		}

		public String next() {

			StringBuilder res = new StringBuilder();

			while (c <= 32)

				c = getChar();

			while (c > 32) {

				res.append(c);

				c = getChar();

			}

			return res.toString();

		}

		public String nextLine() {

			StringBuilder res = new StringBuilder();

			while (c <= 32)

				c = getChar();

			while (c != '\n') {

				res.append(c);

				c = getChar();

			}

			return res.toString();

		}

		public boolean hasNext() {

			if (c > 32)

				return true;

			while (true) {

				c = getChar();

				if (c == NC)

					return false;

				else if (c > 32)

					return true;

			}

		}

	}

	//	For Input.txt and Output.txt

	//	FileInputStream in = new FileInputStream("input.txt");

	//	FileOutputStream out = new FileOutputStream("output.txt");

	//	PrintWriter pw = new PrintWriter(out);

	//	Scanner sc = new Scanner(in);

}


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

/*

    Author: Anthony Ngene

    Created: 06/10/2020 - 07:03

*/

import java.io.*;

import java.util.*;

public class G {

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

    void solver() throws IOException {

        int n = in.intNext(), k = in.intNext();

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

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

        Tuple[] roads = new Tuple[n - 1];

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

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

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

            nodes[a]++;

            nodes[b]++;

            Tuple road = new Tuple(a, b);

            roads[i] = road;

            adj[a].add(road);

            adj[b].add(road);

        }

//        out.println(nodes);

        int lo = 0;

        int hi = n - 1;

        int valid = 0;

        while (lo <= hi) {

            int mid = (lo + hi) / 2;

            int over = 0;

            for (int i = 1; i < n + 1; i++) if (nodes[i] > mid) over++;

            if (over <= k) {

                valid = mid;

                hi = mid - 1;

            } else

                lo = mid + 1;

        }

        out.println(valid);

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

        Deque<Integer> deque = new ArrayDeque<>();

        deque.addLast(1);

        nodes[1] = -1;

        int owner = 0;

        while (!deque.isEmpty()) {

            int idx = deque.pollFirst();

            visited[idx] = true;

            int prev = nodes[idx];

            for (Tuple child : adj[idx]) {

                int other = child.a == idx ? child.b : child.a;

                if (visited[other]) continue;

                if (owner == prev) owner = (owner + 1) % valid;

                nodes[other] = owner;

                child.c = owner;

                owner = (owner + 1) % valid;

                deque.addLast(other);

            }

        }

        for (int i = 0; i < n - 1; i++) out.p(roads[i].c + 1).p(" ");

    }

// Generated Code Below:

private static final FastWriter out = new FastWriter();

private static FastScanner in;

static ArrayList<Integer>[] adj;

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

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

    in = new FastScanner();

    new G().solver();

    out.close();

}

static class FastWriter {

    private static final int IO_BUFFERS = 128 * 1024;

    private final StringBuilder out;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public void toFile(String fileName) throws IOException {

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

        writer.write(out.toString());

        writer.close();

    }

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

}

static class FastScanner {

    private InputStream sin = System.in;

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

    private int ptr = 0;

    private int buflen = 0;

    public FastScanner(){}

    public FastScanner(String filename) throws FileNotFoundException {

        File file = new File(filename);

        sin = new FileInputStream(file);

    }

    private boolean hasNextByte() {

        if (ptr < buflen) {

            return true;

        }else{

            ptr = 0;

            try {

                buflen = sin.read(buffer);

            } catch (IOException e) {

                e.printStackTrace();

            }

            if (buflen <= 0) {

                return false;

            }

        }

        return true;

    }

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

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

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

    public String next() {

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

        StringBuilder sb = new StringBuilder();

        int b = readByte();

        while(isPrintableChar(b)) {

            sb.appendCodePoint(b);

            b = readByte();

        }

        return sb.toString();

    }

    public long longNext() {

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

        long n = 0;

        boolean minus = false;

        int b = readByte();

        if (b == '-') {

            minus = true;

            b = readByte();

        }

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

            throw new NumberFormatException();

        }

        while(true){

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

                n *= 10;

                n += b - '0';

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

                return minus ? -n : n;

            }else{

                throw new NumberFormatException();

            }

            b = readByte();

        }

    }

    public int intNext() {

        long nl = longNext();

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

        return (int) nl;

    }

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

    public long[] nextLongArray(final int n){

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

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

            a[i] = longNext();

        return a;

    }

    public int[] nextIntArray(final int n){

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

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

            a[i] = intNext();

        return a;

    }

    public double[] nextDoubleArray(final int n){

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

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

            a[i] = doubleNext();

        return a;

    }

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

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

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

        return adj;

    }

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

        return adjacencyList(nodes, edges, false);

    }

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

        adj = getAdj(nodes);

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

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

            adj[a].add(b);

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

        }

        return adj;

    }

}

static class u {

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

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

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

        while (r - l >= 0) {

            int c = (l + r) / 2;

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

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

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

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

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

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

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

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

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

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

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

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

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

            }

        });

    }

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

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

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

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

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

        while (left < right) {

            int temp = arr[left];

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

            arr[right--] = temp;

        }

        return arr;

    }

    public static boolean findNextPermutation(int[] data) {

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

        int last = data.length - 2;

        while (last >= 0) {

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

            last--;

        }

        if (last < 0) return false;

        int nextGreater = data.length - 1;

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

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

                nextGreater = i;

                break;

            }

        }

        data = swap(data, nextGreater, last);

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

        return true;

    }

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

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

        int mid=-1;

        while(left<=right){

            mid = (right+left)/2;

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

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

            else right=mid-1;

        }

        return -1;

    }

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

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

        int mid=-1;

        while((right-left)>1){

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

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

            else right=mid;

        }

        return left;

    }

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

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

        int mid=-1;

        while((right-left)>1){

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

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

            else right=mid;

        }

        return left;

    }

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

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

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

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

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

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

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

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

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

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

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

        if(a!=b) return false;

        if(b!=c) return false;

        if(c!=a) return false;

        return true;

    }

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

        if(a==b) return false;

        if(b==c) return false;

        if(c==a) return false;

        return true;

    }

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

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

    }

    private static long factorial(int n) {

        long ans=1;

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

        return ans;

    }

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

        long ans=1;

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

        return ans;

    }

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

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

        ans *= n;

        return ans;

    }

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

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

        if(n == 0) return m;

        return gcd(n, m % n);

    }

    private static boolean isPrime(long a){

        if(a==1) return false;

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

        return true;

    }

    static long modInverse(long a, long mod) {

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

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

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

    }

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

        long res = 1;

        while (b > 0) {

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

            a = (a * a) % mod;

            b /= 2;

        }

        return res;

    }

    private static int getDigit2(long num){

        long cf = 1;    int d=0;

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

        return d;

    }

    private static int getDigit10(long num){

        long cf = 1;    int d=0;

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

        return d;

    }

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

        if(y<0) return false;

        if(x<0) return false;

        if(y>=h) return false;

        if(x>=w) return false;

        return true;

    }

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

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

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

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

            if (lp[i] == 0) {

                lp[i] = i;

                pr.add(i);

            }

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

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

            }

        }

        return pr;

    }

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

        long res = 1;

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

            res = (res * i) % MOD;

        }

        return res;

    }

    static long nCr(int n, int r) {

        if (r > (n - r))

            r = n - r;

        long ans = 1;

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

            ans *= n;

            ans /= i;

            n--;

        }

        return ans;

    }

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

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

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

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

        return  (first * second) % MOD;

    }

    static void printBitRepr(int n) {

        StringBuilder res = new StringBuilder();

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

            int mask = (1 << i);

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

        }

        out.println(res);

    }

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

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

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

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

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

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

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

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

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

        return counts;

    }

    static long hash(int x, int y) {

        return x* 1_000_000_000L +y;

    }

    static final Random random = new Random();

    static void sort(int[] a) {

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

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

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

            a[oi] = a[i];

            a[i] = temp;

        }

        Arrays.sort(a);

    }

    static void sort(long[] arr) {

        shuffleArray(arr);

        Arrays.sort(arr);

    }

    static void shuffleArray(long[] arr) {

        int n = arr.length;

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

            long tmp = arr[i];

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

            arr[i] = arr[randomPos];

            arr[randomPos] = tmp;

        }

    }

}

static class Tuple implements Comparable<Tuple> {

    int a;

    int b;

    int c;

    public Tuple(int a, int b) {

        this.a = a;

        this.b = b;

        this.c = 0;

    }

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

        this.a = a;

        this.b = b;

        this.c = c;

    }

    public int getA() { return a; }

    public int getB() { return b; }

    public int getC() { return c; }

    public int compareTo(Tuple other) {

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

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

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

        }

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

    }

    @Override

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

    @Override

    public boolean equals(Object o) {

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

        Tuple pairo = (Tuple) o;

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

    }

    @Override

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

}

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

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

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

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

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

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

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

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

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

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

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

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

}


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

import java.util.*;

import java.io.*;

public class Main {

    void solve() {

        int n = in.nextInt();

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

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

            arr[i] = in.nextInt();

        }

        HashMap<Long, List<int[]>> map = new HashMap<>();

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

            long sum = 0l;

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

                sum += arr[j];

                map.computeIfAbsent(sum, k -> new ArrayList<>()).add(new int[] {i, j});

            }

        }

        List<int[]> ans = new ArrayList<>();

        for (Map.Entry<Long, List<int[]>> x : map.entrySet()) {

            List<int[]> cur = x.getValue();

            Collections.sort(cur, Comparator.comparingInt(a -> a[1]));

            List<int[]> temp = new LinkedList<>();

            int prev =0;

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

                if (cur.get(i)[0] > prev) {

                    temp.add(cur.get(i));

                    prev = cur.get(i)[1];

                }

            }

            if (temp.size() > ans.size()) {

                ans = temp;

            }

        }

        out.println(ans.size());

        for (int[] x : ans) {

            out.println(x[0]+" "+x[1]);

        }

    }

    FastScanner in;

    PrintWriter out;

    void run() {

        in = new FastScanner();

        out = new PrintWriter(System.out);

        solve();

        out.close();

    }

    class FastScanner {

        BufferedReader br;

        StringTokenizer st;

        public FastScanner() {

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

        }

        public FastScanner(String s) {

            try {

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

            } catch (FileNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

        public String nextToken() {

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

                try {

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

                } catch (IOException e) {

                }

            }

            return st.nextToken();

        }

        public int nextInt() {

            return Integer.parseInt(nextToken());

        }

        public long nextLong() {

            return Long.parseLong(nextToken());

        }

        public double nextDouble() {

            return Double.parseDouble(nextToken());

        }

    }

    public static void main(String[] args) {

        new Main().run();

    }

}


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

import java.io.*;

import java.nio.file.FileStore;

import java.util.*;

 public class zia

 {

	static void BFS(ArrayList<ArrayList<Integer>> adj,int s, boolean[] visited)

	{

    	Queue<Integer> q=new LinkedList<>();

    	visited[s] = true;

    	q.add(s);

    	while(q.isEmpty()==false)

    	{

    		int u = q.poll();

    		for(int v:adj.get(u)){

    		    if(visited[v]==false){

    		        visited[v]=true;

    		        q.add(v);

    		    }

    		}

    	}

	}

	// static int BFS(ArrayList<ArrayList<Integer>> adj,pair s, boolean[] visited,int ar[],int m)

	// {

    // 	Queue<pair> q=new LinkedList<>();

    // 	visited[s.a] = true;

    // 	q.add(s);

	// 	int count=0;

    // 	while(q.isEmpty()==false)

    // 	{

    // 		pair u = q.poll();

	// 		// if(adj.get(u.a).size()==0)

	// 		// count++;

	// 		boolean end=true;

    // 		for(int v:adj.get(u.a)){

    // 		    if(visited[v]==false){

    // 		        visited[v]=true;

	// 				end=false;

	// 				int cat=ar[v]==0?0:ar[v]+u.b;

	// 				if(cat>m)

	// 				continue;

    // 		        q.add(new pair(v, cat));

	// 				// System.out.print("--"+v+" "+cat+"--");

    // 		    }

    // 		}

	// 		if(end)

	// 		count++;

	// 		// System.out.println(u.a+" "+adj.get(u.a).size()+" count "+count);

    // 	}

	// 	return count;

	// }

	static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v)

	{

		adj.get(u).add(v);

		adj.get(v).add(u);

	}

	static void ruffleSort(long[] a) {

        int n=a.length;

		Random random = new Random();

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

            int oi=random.nextInt(n);

			long temp=a[oi];

            a[oi]=a[i]; a[i]=temp;

        }

        Arrays.sort(a);

    }

	static void ruffleSort(int[] a) {

        int n=a.length;

		Random random = new Random();

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

            int oi=random.nextInt(n);

			int temp=a[oi];

            a[oi]=a[i]; a[i]=temp;

        }

        Arrays.sort(a);

    }

	public static int Lcm(int a,int b)

	{ int max=Math.max(a,b);

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

		{

			if((max*i)%a==0&&(max*i)%b==0)

			return (max*i);

		}

	}

  static void sieve(int n,boolean prime[])

    {

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

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

            prime[i] = true;

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

            if (prime[p] == true) {

                for (int i = p * p; i <= n; i =i+ p)

                    prime[i] = false;

            }

        }

    }

	// public static String run(int ar[],int n)

	// {

	// }

	public static int upperbound(int s,int e, long ar[],long x)

	{

		int res=-1;

		while(s<=e)

		{ int mid=((s-e)/2)+e;

			if(ar[mid]>x)

			{e=mid-1;res=mid;}

			else if(ar[mid]<x)

			{s=mid+1;}

			else

			{e=mid-1;res=mid;

			 if(mid>0&&ar[mid]==ar[mid-1])

			 e=mid-1;

			 else

			 break;

			}

		}

		return res;

	}

	public static long lowerbound(int s,int e, long ar[],long x)

	{

		long res=-1;

		while(s<=e)

		{ int mid=((s-e)/2)+e;

			if(ar[mid]>x)

			{e=mid-1;}

			else if(ar[mid]<x)

			{s=mid+1;res=mid;}

			else

			{res=mid;

				if(mid+1<ar.length&&ar[mid]==ar[mid+1])

			    s=mid+1;

			    else

				break;}

		}

		return res;

	}

	static long modulo=1000000007;

	public static long power(long a, long b)

	{

		if(b==0) return 1;

		long temp=power(a,b/2)%modulo;

		if((b&1)==0)

		return (temp*temp)%modulo;

		else

		return (((temp*temp)%modulo)*a)%modulo;

	}

	public static long powerwithoutmod(long a, long b)

	{

		if(b==0) return 1;

		long temp=power(a,b/2);

		if((b&1)==0)

		return (temp*temp);

		else

		return ((temp*temp)*a);

	}

	public static double log2(long a)

	{ double d=Math.log(a)/Math.log(2);

		return d;

	}

	public static int log10(long a)

	{ double d=Math.log(a)/Math.log(10);

		return (int)d;

	}

	public static long gcd(long a, long b)

    {

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

	public static void tree(int s,int e,int ar[],int c)

	{

	  if(s<=e)

	  {

		  int max=s;

		  for(int i=s;i<=e;i++)

		   if(ar[i]>ar[max])

			 max=i;

		  ar[max]=c++;

		  tree(s,max-1,ar,c);

		  tree(max+1,e,ar,c);

	  }

	}

 static int resturant=0;

 static void DFS(ArrayList<ArrayList<Integer>> al,boolean visited[],int s,int max,int curr,int ar[])

 {

	visited[s]=true;

	if(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)

	{resturant++;return;}

	// System.out.println(s+" "+curr);

	for(int x:al.get(s))

	{

		if(visited[x]==false)

		{

			if(ar[x]==0)

			DFS(al, visited, x, max, 0, ar);

			else if(curr+ar[x]<=max)

			DFS(al, visited, x, max, curr+ar[x], ar);

		}

	}

 }

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

   {

		FastIO sc = new FastIO();

		//sc.println();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

		int test=sc.nextInt();

		// // double c=Math.log(10);

		// boolean prime[]=new boolean[233334];

		// sieve(233334, prime);

		// HashMap<Character,Integer> hm=new HashMap<>(9);

		// char c='1';

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

		//  hm.put(c++,i);

		while(test-->0)

		{

			int n=sc.nextInt();

			long in=sc.nextLong();

			triplet ar[]=new triplet[n];

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

			  ar[i]=new triplet(sc.nextLong(),sc.nextLong(),sc.nextLong());

			Arrays.sort(ar);

			long s=in,e=in;

			String res="YES";

			// sc.println(s+"--"+e);

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

			{

				long deltaT=ar[i].first;

				if(i!=0)

				deltaT-=ar[i-1].first;

				long currs=s-deltaT,curre=e+deltaT;

				if(currs>ar[i].third||curre<ar[i].second)

				{

					res="NO";

					break;

				}

				s=Math.max(currs, ar[i].second);

				e=Math.min(curre, ar[i].third);

				// sc.println(s+" "+e);

			}

			sc.println(res);

		}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

sc.close();

}

}

class pair implements Comparable<pair>{

	int a;

	int b;

	pair(int a,int b)

	{this.a=a;

		this.b=b;

	}

	public int compareTo(pair p)

	{

		if(this.a-p.a==0)

		return this.b-p.b;

		return (this.a-p.a);

	}

}

class triplet implements Comparable<triplet>{

	long first,second,third;

	triplet(long first,long second,long third)

	{this.first=first;

		this.second=second;

		this.third=third;

	}

	public int compareTo(triplet p)

	{

		return (int)(this.first-p.first);

	}

}

// class triplet

// {

// 	int x1,x2,i;

// 	triplet(int a,int b,int c)

// 	{x1=a;x2=b;i=c;}

// }

 class FastIO extends PrintWriter {

	private InputStream stream;

	private byte[] buf = new byte[1<<16];

	private int curChar, numChars;

	// standard input

	public FastIO() { this(System.in,System.out); }

	public FastIO(InputStream i, OutputStream o) {

		super(o);

		stream = i;

	}

	// file input

	public FastIO(String i, String o) throws IOException {

		super(new FileWriter(o));

		stream = new FileInputStream(i);

	}

	// throws InputMismatchException() if previously detected end of file

	private int nextByte() {

		if (numChars == -1) throw new InputMismatchException();

		if (curChar >= numChars) {

			curChar = 0;

			try {

				numChars = stream.read(buf);

			} catch (IOException e) {

				throw new InputMismatchException();

			}

			if (numChars == -1) return -1; // end of file

		}

		return buf[curChar++];

	}

	public String nextLine() {

		int c; do { c = nextByte(); } while (c <= '\n');

		StringBuilder res = new StringBuilder();

		do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');

		return res.toString();

	}

	public String next() {

		int c; do { c = nextByte(); } while (c <= ' ');

		StringBuilder res = new StringBuilder();

		do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');

		return res.toString();

	}

	public int nextInt() {

		int c; do { c = nextByte(); } while (c <= ' ');

		int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }

		int res = 0;

		do {

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

				throw new InputMismatchException();

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

			c = nextByte();

		} while (c > ' ');

		return res * sgn;

	}

  public long nextLong() {

		int c; do { c = nextByte(); } while (c <= ' ');

		long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }

		long res = 0;

		do {

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

				throw new InputMismatchException();

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

			c = nextByte();

		} while (c > ' ');

		return res * sgn;

	}

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

}


B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows:  However, the results of the Olympiad could also look like this:  In the first case Nikolay would have taken first place, and in the second — third place.

import java.util.Scanner;

public class IntTree {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int t = s.nextInt();

        while(t-->0){

            int n=s.nextInt();

            int x=s.nextInt();

            int y=s.nextInt();

            int min=Math.max(1,Math.min(n,x+y-n+1));

            int max=Math.min(n,x+y-1);

            System.out.println(min+" "+max);

        }

    }

}


C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:   z=acacez=acace (if we choose subsequence aceace);  z=acbcdz=acbcd (if we choose subsequence bcdbcd);  z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class C_Obtain_The_String {

    static long mod = Long.MAX_VALUE;

    static OutputStream outputStream = System.out;

    static PrintWriter out = new PrintWriter(outputStream);

    static FastReader f = new FastReader();

    public static void main(String[] args) {

        int t = f.nextInt();

        while(t-- > 0){

            solve();

        }

        out.close();

    }

    public static void solve() {

        String s = f.nextLine();

        int sl = s.length();

        String t = f.nextLine();

        int tl = t.length();

        ArrayList<TreeSet<Integer>> arrli = new ArrayList<>();

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

            arrli.add(new TreeSet<>());

        }

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

            arrli.get(s.charAt(i)-'a').add(i);

        }

        int ops = 1;

        int ind = 0;

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

            int c = t.charAt(i)-'a';

            if(arrli.get(c).isEmpty()) {

                out.println(-1);

                return;

            }

            Integer nextInd = arrli.get(c).ceiling(ind);

            if(nextInd == null) {

                ops++;

                ind = arrli.get(c).first()+1;

            } else {

                ind = nextInd+1;

            }

        }

        out.println(ops);

    }

    // Sort an array

    public static void sort(int arr[]) {

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

        for(int i: arr) {

            al.add(i);

        }

        Collections.sort(al);

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

            arr[i] = al.get(i);

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

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

            if(n%i == 0) {

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

                if(i != n/i) {

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

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

        if(n % 2 == 0 || n % 3 == 0) return false;

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

            if(n % i == 0 || n % (i+2) == 0) {

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

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

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

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

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

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

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

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

        long res = 1;

        while(b > 0) {

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

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

    public static long nCr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / (fact(r) * fact(n-r));

        return ans;

    }

    // Find nPr

    public static long nPr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / fact(r);

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

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

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextArray(int n) {

            int[] a = new int[n];

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

                a[i] = nextInt();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */

// (a/b)%mod == (a * moduloInverse(b)) % mod;

// moduloInverse(b) = power(b, mod-2);


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

/**
 * @author derrick20
 */
import java.io.*;
import java.util.*;

public class TimeToRun {
    public static void main(String[] args) throws Exception {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        int N = sc.nextInt();
        int M = sc.nextInt();
        int K = sc.nextInt();

        if (K > 4 * M * N - 2 * M - 2 * N) {
            out.println("NO");
        }
        else {
            ArrayList<Integer> f = new ArrayList<>();
            ArrayList<Character> dir = new ArrayList<>();
            for (int i = 0; i < M - 1; i++) {
                if (N > 1) {
                    f.add(N - 1);
                    dir.add('D');
                    f.add(N - 1);
                    dir.add('U');
                }
                f.add(1);
                dir.add('R');
            }
            for (int i = 0; i < N - 1; i++) {
                f.add(1);
                dir.add('D');
                if (M > 1) {
                    f.add(M - 1);
                    dir.add('L');
                    f.add(M - 1);
                    dir.add('R');
                }
            }
            if (N > 1) {
                f.add(N - 1);
                dir.add('U');
            }
            if (M > 1) {
                f.add(M - 1);
                dir.add('L');
            }

            int steps = 0;
            int ptr = 0;
            ArrayList<Integer> ansSteps = new ArrayList<>();
            ArrayList<Character> ansDir = new ArrayList<>();
            while (ptr < f.size() && steps + f.get(ptr) <= K) {
                steps += f.get(ptr);
                ansSteps.add(f.get(ptr));
                ansDir.add(dir.get(ptr));
                ptr++;
            }
            if (steps < K) {
                ansSteps.add(K - steps);
                ansDir.add(dir.get(ptr));
            }
            out.println("YES");
            out.println(ansSteps.size());
            for (int i = 0; i < ansSteps.size(); i++) {
                out.println(ansSteps.get(i) + " " + ansDir.get(i));
            }
        }

        out.close();
    }

    static class FastScanner {
        private int BS = 1<<16;
        private char NC = (char)0;
        private byte[] buf = new byte[BS];
        private int bId = 0, size = 0;
        private char c = NC;
        private double cnt = 1;
        private BufferedInputStream in;

        public FastScanner() {
            in = new BufferedInputStream(System.in, BS);
        }

        public FastScanner(String s) {
            try {
                in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
            }
            catch (Exception e) {
                in = new BufferedInputStream(System.in, BS);
            }
        }

        private char getChar(){
            while(bId==size) {
                try {
                    size = in.read(buf);
                }catch(Exception e) {
                    return NC;
                }
                if(size==-1)return NC;
                bId=0;
            }
            return (char)buf[bId++];
        }

        public int nextInt() {
            return (int)nextLong();
        }

        public int[] nextInts(int N) {
            int[] res = new int[N];
            for (int i = 0; i < N; i++) {
                res[i] = (int) nextLong();
            }
            return res;
        }

        public long[] nextLongs(int N) {
            long[] res = new long[N];
            for (int i = 0; i < N; i++) {
                res[i] = nextLong();
            }
            return res;
        }

        public long nextLong() {
            cnt=1;
            boolean neg = false;
            if(c==NC)c=getChar();
            for(;(c<'0' || c>'9'); c = getChar()) {
                if(c=='-')neg=true;
            }
            long res = 0;
            for(; c>='0' && c <='9'; c=getChar()) {
                res = (res<<3)+(res<<1)+c-'0';
                cnt*=10;
            }
            return neg?-res:res;
        }

        public double nextDouble() {
            double cur = nextLong();
            return c!='.' ? cur:cur+nextLong()/cnt;
        }

        public String next() {
            StringBuilder res = new StringBuilder();
            while(c<=32)c=getChar();
            while(c>32) {
                res.append(c);
                c=getChar();
            }
            return res.toString();
        }

        public String nextLine() {
            StringBuilder res = new StringBuilder();
            while(c<=32)c=getChar();
            while(c!='\n') {
                res.append(c);
                c=getChar();
            }
            return res.toString();
        }

        public boolean hasNext() {
            if(c>32)return true;
            while(true) {
                c=getChar();
                if(c==NC)return false;
                else if(c>32)return true;
            }
        }
    }
}


D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3

3

4

4

OutputCopy

? 5 6

? 3 1

? 1 2

! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

import java.util.*;

import java.io.*;

public class OTCD {

    public static void main(String[] args) {

        MyScanner sc = new MyScanner();

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

        int n = sc.nextInt();

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

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

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

            int x = sc.nextInt(); int y = sc.nextInt();

            adj[x].add(y); adj[y].add(x);

        }

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

        while (true) {

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

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

                if (!bad[i] && adj[i].size() == 1) a.add(i);

                if (a.size() == 2) break;

            }

            if (a.size() == 0) {

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

                    if (adj[i].size() == 0) {

                        System.out.println("! " + i); return;

                    }

                }

            }

            System.out.println("? "  + a.get(0) + " " + a.get(1));

            System.out.flush();

            int lca = sc.nextInt();

            if (lca == a.get(0) || lca == a.get(1)) {

                System.out.println("! " + lca);

                return;

            } else {

                adj[adj[a.get(0)].get(0)].remove(a.get(0));

                adj[adj[a.get(1)].get(0)].remove(a.get(1));

                bad[a.get(0)] = true; bad[a.get(1)] = true;

            }

        }

        //out.close();

    }

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

    public static class MyScanner {

        BufferedReader br;

        StringTokenizer st;

        public MyScanner() {

            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;

        }

    }

}


E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.

//created by Whiplash99

import java.io.*;

import java.util.*;

public class E

{

    private static final int lim=(int)(1e6+5);

    private static int[] dist, parent, spf;

    private static ArrayList<Integer> edge[], vis;

    private static void sieve()

    {

        for(int i=2;i<lim;i++)

        {

            if(spf[i]==0)

            {

                spf[i]=i;

                if((long)i*i<lim)

                    for(int j=i*i;j<lim;j+=i)

                    {

                        if(spf[j]==0)

                            spf[j]=i;

                    }

            }

        }

    }

    private static int normalise(int N)

    {

        int val=1;

        while (N>1)

        {

            int f=spf[N];

            int c=0;

            while (spf[N]==f)

            {

                c^=1;

                N/=f;

            }

            if(c==1) val*=f;

        }

        return val;

    }

    private static int cycleLength(int u)

    {

        vis.clear();

        vis.add(u);

        dist[u]=0;

        int ans=-1;

        ArrayDeque<Integer> queue=new ArrayDeque<>();

        queue.add(u);

        while (ans==-1&&!queue.isEmpty())

        {

            int v=queue.poll();

            for(int child:edge[v])

            {

                if(dist[child]==-1)

                {

                    dist[child]=dist[v]+1;

                    parent[child]=v;

                    vis.add(child);

                    queue.add(child);

                }

                else if(parent[v]!=child)

                {

                    ans=dist[v]+dist[child]+1;

                    break;

                }

            }

        }

        for(int i:vis) dist[i]=-1;

        return ans;

    }

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

    {

        Reader r=new Reader();

        int i,N;

        vis=new ArrayList<>();

        spf=new int[lim];

        dist=new int[lim];

        parent=new int[lim];

        edge=new ArrayList[lim];

        for(i=0;i<lim;i++) edge[i]=new ArrayList<>();

        Arrays.fill(dist,-1);

        sieve();

        N=r.nextInt();

        int a[]=new int[N];

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

            a[i]=r.nextInt();

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

        {

            a[i]=normalise(a[i]);

            if(a[i]==1)

            {

                System.out.println(1);

                System.exit(0);

            }

            int u=spf[a[i]];

            int v=a[i]/u;

            edge[u].add(v);

            edge[v].add(u);

        }

        for(i=0;i<lim;i++)

        {

            Collections.sort(edge[i]);

            for(int j=0;j<edge[i].size()-1;j++)

            {

                if(edge[i].get(j)==edge[i].get(j+1))

                {

                    System.out.println(2);

                    System.exit(0);

                }

            }

        }

        int ans=lim;

        for(i=1;i<=1000;i++)

        {

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

            int tmp=cycleLength(i);

            if(tmp!=-1) ans=Math.min(ans,tmp);

        }

        System.out.println(ans==lim?-1:ans);

    }

    static class Reader

    {

        final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;

        public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;

        }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;

        }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);

        }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;

        }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;

        }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;

        }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;

        }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];

        }public void close() throws IOException{if(din==null) return;din.close();}

    }

}