A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.

The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.

In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.

NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.

// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
	//Fast IO class
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
        	boolean env=System.getProperty("ONLINE_JUDGE") != null;
        	if(!env) {
        		try {
					br=new BufferedReader(new FileReader("src\\input.txt"));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
        	}
        	else br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static long MOD=1000000000+7;
    //debug
    static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
    // Pair
    static class pair{
    	long x,y;
    	pair(long a,long b){
    		this.x=a;
    		this.y=b;
    	}
    	public boolean equals(Object obj) {
    		if(obj == null || obj.getClass()!= this.getClass()) return false;
            pair p = (pair) obj;
            return (this.x==p.x && this.y==p.y);
        }
    	public int hashCode() {
            return Objects.hash(x,y);
        }
    }
    static FastReader sc=new FastReader();
    static PrintWriter out=new PrintWriter(System.out);
    //Main function(The main code starts from here)
    static int n,k;
    static long val=0;
    static long a[];
    static boolean check(int x) {
    	long sum=0;
    	val=a[x-1];
    	for(int i=0;i<x;i++) sum+=a[i];
    	if(val*x-sum<=k) return true;
    	for(int i=x;i<n;i++) {
    		sum=sum+a[i]-a[i-x];
    		val=a[i];
    		if(val*x-sum<=k) return true;
    	}
    	return false;
    }
    public static void main (String[] args) throws java.lang.Exception {
    	int test=1;
    	//test=sc.nextInt();
    	while(test-->0){
    		n=sc.nextInt();k=sc.nextInt();a=new long[n];
    		for(int i=0;i<n;i++) a[i]=sc.nextLong();
    		Arrays.parallelSort(a);
    		int l=1,r=n,ans=1;
    		while(l<=r) {
    			int mid=l+(r-l)/2;
    			if(check(mid)) {
    				ans=mid;
    				l=mid+1;
    			}
    			else r=mid-1;
    		}
    		check(ans);
    		out.println(ans+" "+val);
    	}
        out.flush();
        out.close();
    }
}


There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

/**
 * ******* Created on 19/9/19 3:33 AM*******
 */

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

public class B7 {
    public static void main(String[] args) throws IOException {
        try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            int t = input.nextInt();
            int m = input.nextInt();
            int[] arr = new int[m];
            for(int i=0;i<m;i++) {
                arr[i]=0;
            }
            int id =0;
            while(t-- >0){
                String s = input.next();
                if(s.equals("defragment")){
                    for(int i=0, j=0;i<m;i++){
                        if(arr[j]!=0)j++;
                        if(arr[i]!=0 && j <i){
                            arr[j]= arr[i];
                            arr[i]=0;
                            j++;
                        }
                    }
                }else if(s.equals("alloc")){
                    int size = input.nextInt();
                    int cnt1 =0, pos =-1;
                    for(int i=0;i<m;i++){
                        if(arr[i]==0)cnt1++;
                        else cnt1 =0;
                        if(cnt1 ==size){
                            id++;
                            pos =i;
                            break;
                        }
                    }
                    if(pos ==-1){
                        System.out.println("NULL");
                    }else{
                        System.out.println(id);
                        for(int i=pos, k=0;k<size;k++,i--)
                            arr[i]=id;
                    }
                }else{
                    int ids = input.nextInt();
                    boolean flag =false;
                    for(int i=0;i<m;i++){
                        if(arr[i]==ids){
                            flag =true;
                            arr[i]=0;
                        }
                    }
                    if(!flag || ids <=0){
                        System.out.println("ILLEGAL_ERASE_ARGUMENT");
                    }
                }
            }
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

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

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

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

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}

[{'input': '6 10\r\nalloc 5\r\nalloc 3\r\nerase 1\r\nalloc 6\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\n']}, {'input': '6 1\r\ndefragment\r\nalloc 10\r\nalloc 1\r\nerase -1\r\nerase 1\r\nerase 1\r\n', 'output': ['NULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '14 100\r\nalloc 99\r\nalloc 1\r\nalloc 1\r\nerase 2\r\nalloc 1\r\nerase 4\r\nerase 1\r\nalloc 100\r\nalloc 1\r\nalloc 99\r\ndefragment\r\nerase 4\r\nalloc 100\r\nalloc 99\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n4\r\nNULL\r\nNULL\r\nNULL\r\n']}, {'input': '26 25\r\ndefragment\r\nerase 1\r\nerase -1560200883\r\nalloc 44\r\ndefragment\r\nalloc 75\r\nalloc 22\r\ndefragment\r\nerase 4\r\ndefragment\r\nalloc 57\r\nalloc 53\r\nerase 4\r\nerase -1639632026\r\nerase -2121605039\r\nerase 3\r\nalloc 51\r\nalloc 65\r\ndefragment\r\nerase 2\r\nerase 4\r\nalloc 52\r\nerase 3\r\ndefragment\r\nerase -1842529282\r\nerase 3\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '22 9\r\nerase 1\r\nalloc 6\r\nalloc 65\r\nerase 1\r\nalloc 87\r\nerase -1638927047\r\nalloc 5\r\nerase 2\r\nalloc 70\r\ndefragment\r\nalloc 20\r\nalloc 48\r\nerase -69401977\r\nalloc 20\r\ndefragment\r\nerase 7\r\ndefragment\r\nerase 9\r\nerase 7\r\nerase 4\r\ndefragment\r\nalloc 66\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '12 40\r\nerase 1\r\nalloc 21\r\nalloc 5\r\nalloc 7\r\ndefragment\r\ndefragment\r\nerase 2\r\nalloc 83\r\nerase 4\r\ndefragment\r\nalloc 59\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\n2\r\n3\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '38 18\r\nalloc 72\r\nerase 2\r\nalloc 50\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 43\r\nalloc 41\r\ndefragment\r\ndefragment\r\nalloc 26\r\nalloc 46\r\nalloc 16\r\nalloc 15\r\ndefragment\r\ndefragment\r\nalloc 95\r\nerase 7\r\nerase 7\r\nerase 5\r\nerase 2\r\nerase 9\r\nerase 7\r\nalloc 43\r\ndefragment\r\nerase 7\r\ndefragment\r\nalloc 48\r\nalloc 77\r\nerase 10\r\nerase 11\r\nalloc 16\r\nalloc 84\r\nerase 1\r\ndefragment\r\nalloc 86\r\ndefragment\r\nerase 13\r\n', 'output': ['NULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nNULL\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '37 74\r\nalloc 11\r\ndefragment\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 90\r\nerase 3\r\nerase 2\r\nerase 3\r\nerase 1\r\nerase 1\r\nalloc 38\r\nalloc 19\r\nerase 1\r\nerase 3\r\ndefragment\r\nalloc 93\r\nerase 5\r\nerase 4\r\nalloc 66\r\nalloc 71\r\nerase 5\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 7\r\nalloc 47\r\nerase -95616683\r\nerase 2\r\nalloc 28\r\nalloc 32\r\nerase 11\r\nalloc 50\r\ndefragment\r\ndefragment\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\n5\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 49\r\nerase -751005193\r\ndefragment\r\nalloc 37\r\nalloc 82\r\nerase 3\r\nerase 1\r\nalloc 80\r\nalloc 51\r\ndefragment\r\nalloc 74\r\nerase 1\r\nalloc 91\r\ndefragment\r\ndefragment\r\nalloc 98\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '42 98\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 5\r\nalloc 66\r\ndefragment\r\nerase 3\r\nalloc 53\r\ndefragment\r\nerase 4\r\nerase 2\r\nalloc 70\r\nerase 3\r\ndefragment\r\ndefragment\r\nerase 2\r\nerase 3\r\nerase -1327931832\r\nalloc 93\r\nalloc 64\r\nerase 7\r\nerase 6\r\nerase 3\r\nalloc 61\r\nalloc 12\r\nalloc 65\r\nerase 2\r\nalloc 46\r\nerase 11\r\nerase 9\r\nerase 9\r\nerase 6\r\nalloc 2\r\nalloc 78\r\ndefragment\r\nerase 13\r\nerase 6\r\nerase 10\r\nalloc 53\r\nalloc 46\r\n', 'output': ['1\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '19 46\r\nalloc 21\r\nerase 2\r\nerase 1\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nalloc 40\r\nerase 1\r\ndefragment\r\ndefragment\r\nalloc 68\r\nerase -388966015\r\nalloc 85\r\nalloc 53\r\nerase 4\r\ndefragment\r\nalloc 49\r\nalloc 88\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '44 46\r\nalloc 28\r\nalloc 36\r\ndefragment\r\nerase -937404236\r\nalloc 71\r\ndefragment\r\nalloc 81\r\nalloc 51\r\nerase 3\r\ndefragment\r\nalloc 48\r\nerase 1\r\ndefragment\r\nalloc 36\r\ndefragment\r\ndefragment\r\nerase 1\r\ndefragment\r\ndefragment\r\nerase -1173350787\r\nalloc 94\r\nerase 5\r\ndefragment\r\nerase 9\r\nalloc 98\r\nerase 7\r\ndefragment\r\nerase 5\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nerase 4\r\ndefragment\r\nerase 9\r\nalloc 8\r\ndefragment\r\nerase 9\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 1\r\nalloc 70\r\nerase 9\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '26 25\r\nalloc 25\r\nerase 1\r\nalloc 24\r\nerase 2\r\nalloc 23\r\nerase 3\r\nalloc 24\r\nerase 4\r\nalloc 24\r\nerase 5\r\nalloc 21\r\nerase 6\r\nalloc 24\r\nerase 7\r\nalloc 25\r\nerase 8\r\nalloc 25\r\nerase 9\r\nalloc 24\r\nerase 10\r\nalloc 25\r\nerase 11\r\nalloc 25\r\nerase 12\r\nalloc 25\r\nerase 13\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n']}, {'input': '22 9\r\nalloc 9\r\nerase 1\r\nalloc 9\r\nerase 2\r\nalloc 9\r\nerase 3\r\nalloc 9\r\nerase 4\r\nalloc 9\r\nerase 5\r\nalloc 9\r\nerase 6\r\nalloc 9\r\nerase 7\r\nalloc 9\r\nerase 8\r\nalloc 9\r\nerase 9\r\nalloc 9\r\nerase 10\r\nalloc 9\r\nerase 11\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n']}, {'input': '7 6\r\nalloc 1\r\nalloc 2\r\nalloc 3\r\nerase 1\r\ndefragment\r\nerase 3\r\nalloc 4\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n']}, {'input': '3 1\r\nerase -1\r\nerase 0\r\nerase -2147483648\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '7 100\r\nalloc 100\r\nerase 2147483647\r\nerase 1\r\nalloc 50\r\nalloc 50\r\nerase 3\r\nerase -2147483648\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '12 10\r\nalloc 6\r\nalloc 2\r\nerase 1\r\nalloc 4\r\nalloc 2\r\nerase 3\r\nalloc 2\r\nalloc 3\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\nNULL\r\n6\r\n7\r\n8\r\n9\r\n']}, {'input': '8 50\r\nalloc 51\r\ndefragment\r\nalloc 100\r\ndefragment\r\nerase 1\r\nalloc 50\r\ndefragment\r\nalloc 50\r\n', 'output': ['NULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\n']}, {'input': '10 10\r\nalloc 10\r\nerase -1\r\nerase 1\r\nalloc 5\r\nerase -1\r\nalloc 5\r\nerase 0\r\nalloc 5\r\nerase 0\r\nalloc 5\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\n4\r\n']}]


Reca company makes monitors, the most popular of their models is AB999 with the screen size a × b centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio x: y became popular with users. That's why the company wants to reduce monitor AB999 size so that its screen sides ratio becomes x: y, at the same time they want its total area to be maximal of all possible variants. Your task is to find the screen parameters of the reduced size model, or find out that such a reduction can't be performed.

The first line of the input contains 4 integers — a, b, x and y (1 ≤ a, b, x, y ≤ 2·109).

If the answer exists, output 2 positive integers — screen parameters of the reduced size model. Output 0 0 otherwise.

import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.text.*;
public class cf1 {
    static long mod = (long)1e9 + 7;
    static long mod1 = 998244353;
    static FastScanner f;
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner S = new Scanner(System.in);
    static long x0; static long y0;
    static int inf = (int)(1e9);
    static long iinf = (long)(1e18);
    static void solve()throws IOException {
        long a = f.nl(); long b = f.nl(); long x = f.nl(); long y = f.nl();
        long g = gcd(x , y);
        x /= g; y /= g;
        a = Math.min(a / x , b / y);
        pn(x * a + " " + y * a);
    }
    public static void main(String[] args)throws IOException {
        init();
        int t = 1;
        while(t --> 0) {solve();}
        pw.flush();
        pw.close();
    }

/******************************END OF MAIN PROGRAM*******************************************/
    public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
    public static class FastScanner {
        BufferedReader br;StringTokenizer st;
        FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
        FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
        String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
        String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}
    }
    public static void pn(Object o){pw.println(o);}
    public static void p(Object o){pw.print(o);}
    public static void pni(Object o){pw.println(o);pw.flush();}
    static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
    static long gcd(long a,long b){if(b==0l)return a;else{return gcd(b,a%b);}}
    static long lcm(long a,long b){return (a*b/gcd(a,b));}
    static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
    static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
    static long mpow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=((res%mod)*(a%mod))%mod;b>>=1;a=((a%mod)*(a%mod))%mod;}return res;}
    static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
    static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
    static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> ans=new HashSet<Long>();for(Long i:ff)if(isPrime(i))ans.add(i);return ans;}
    static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> ans=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))ans.add(i);return ans;}
    static int[] inpint(int n){int arr[]=new int[n];for(int i=0;i<n;i++){arr[i]=f.ni();}return arr;}
    static long[] inplong(int n){long arr[] = new long[n];for(int i=0;i<n;i++){arr[i]=f.nl();}return arr;}
    static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
    static int gnv(char c){return Character.getNumericValue(c);}//No. of integers less than equal to i in ub
    static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
    static int upperbound(int a[],int i){int lo=0,hi=a.length-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a[mid]<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;}
    static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(ArrayList<Integer> a){Collections.sort(a);}//!Precompute fact in ncr()!
}


The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces.All puzzle pieces turn out to be of the same size X × Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A × B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.

The first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20. Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters.

In the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself.  In the second line print two numbers — the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly — by the length X.

NoteThe picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4).

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int A = in.nextInt();
            int B = in.nextInt();
            char[][] puzzle = new char[A][B];
            for (int i = 0; i < A; i++) {
                puzzle[i] = in.next().toCharArray();
            }
            PriorityQueue<piece> ans = new PriorityQueue<>();
            for (int Y = 1; Y <= A; Y++) {
                for (int X = 1; X <= B; X++) {
                    if (A % Y == 0 && B % X == 0) {
                        if (chk(puzzle, Y, X)) {
                            ans.offer(new piece(Y, X));
                        }
                    }
                }
            }
            out.println(ans.size());
            out.println(ans.peek());
        }

        boolean chk(char[][] puzzle, int Y, int X) {
            ArrayList<fullPiece> pieces = new ArrayList<>();
            for (int i = 0; i < puzzle.length; i += Y) {
                for (int j = 0; j < puzzle[0].length; j += X) {
                    fullPiece next = new fullPiece(puzzle, Y, X, i, j);
                    for (fullPiece cur : pieces) {
                        if (next.eq(cur)) return false;
                    }
                    pieces.add(next);
                }
            }
            return true;
        }

    }

    static class piece implements Comparable {
        int y;
        int x;

        piece(int y1, int x1) {
            y = y1;
            x = x1;
        }

        public int compareTo(Object o) {
            piece other = (piece) o;
            int oS = other.x * other.y;
            int S = x * y;
            if (S == oS) {
                return y - other.y;
            }
            return S - oS;
        }

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

    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer stt;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public String next() {
            while (stt == null || !stt.hasMoreTokens()) {
                stt = new StringTokenizer(nextLine());
            }
            return stt.nextToken();
        }

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

    }

    static class fullPiece {
        char[][] data;

        fullPiece(char[][] puzzle, int Y, int X, int top, int left) {
            data = new char[Y][X];
            for (int i = 0; i < Y; i++) {
                for (int j = 0; j < X; j++) {
                    data[i][j] = puzzle[i + top][j + left];
                }
            }
        }

        public boolean eq(fullPiece other) {
            return eq0(other) || eq90(other) || eq180(other) || eq270(other);
        }

        private boolean eq0(fullPiece other) {
            int Y = data.length;
            int X = data[0].length;
            for (int i = 0; i < Y; i++) {
                for (int j = 0; j < X; j++) {
                    if (data[i][j] != other.data[i][j]) return false;
                }
            }
            return true;
        }

        private boolean eq180(fullPiece other) {
            int Y = data.length;
            int X = data[0].length;
            for (int i = 0; i < Y; i++) {
                for (int j = 0; j < X; j++) {
                    if (data[Y - i - 1][X - j - 1] != other.data[i][j]) return false;
                }
            }
            return true;
        }

        private boolean eq90(fullPiece other) {
            int Y = data.length;
            int X = data[0].length;
            if (other.data[0].length != Y) return false;
            if (other.data.length != X) return false;
            for (int i = 0; i < Y; i++) {
                for (int j = 0; j < X; j++) {
                    if (data[X - j - 1][i] != other.data[i][j]) return false;
                }
            }
            return true;
        }

        private boolean eq270(fullPiece other) {
            int Y = data.length;
            int X = data[0].length;
            if (other.data[0].length != Y) return false;
            if (other.data.length != X) return false;
            for (int i = 0; i < Y; i++) {
                for (int j = 0; j < X; j++) {
                    if (data[j][Y - i - 1] != other.data[i][j]) return false;
                }
            }
            return true;
        }

    }
}

[{'input': '2 4\r\nABDC\r\nABDC\r\n', 'output': ['3\r\n2 1\r\n']}, {'input': '2 6\r\nABCCBA\r\nABCCBA\r\n', 'output': ['1\r\n2 6\r\n']}, {'input': '2 2\r\nAB\r\nCD\r\n', 'output': ['4\r\n1 1\r\n']}, {'input': '4 6\r\nABABAC\r\nBABABC\r\nABABAC\r\nCCCCCA\r\n', 'output': ['4\r\n2 3\r\n']}, {'input': '1 12\r\nABAAADCAAABX\r\n', 'output': ['4\r\n1 3\r\n']}, {'input': '4 6\r\nABCDEF\r\nGHIJKL\r\nMNOPQR\r\nSTUVWX\r\n', 'output': ['12\r\n1 1\r\n']}, {'input': '5 5\r\nABAAA\r\nBBBAA\r\nABABA\r\nBBABB\r\nBAAAB\r\n', 'output': ['3\r\n1 5\r\n']}, {'input': '5 6\r\nBBBABB\r\nAAAABB\r\nABABAA\r\nABBBAA\r\nBABBBA\r\n', 'output': ['4\r\n1 6\r\n']}, {'input': '7 7\r\nBBAAABB\r\nAABBBBA\r\nAABABBA\r\nAABABAB\r\nAABBBAA\r\nBAAAABA\r\nBBABBBB\r\n', 'output': ['3\r\n1 7\r\n']}, {'input': '8 7\r\nBABABBB\r\nABABABA\r\nAABBABA\r\nABBABAA\r\nBABAAAB\r\nAABBBBA\r\nABBBBAB\r\nBBAAABA\r\n', 'output': ['5\r\n1 7\r\n']}, {'input': '8 9\r\nBAABABAAB\r\nBAABAAAAB\r\nBBBBBAABB\r\nAAAAAAAAB\r\nBABBABBAA\r\nBBABABBBB\r\nBABABBAAA\r\nAABAABBBB\r\n', 'output': ['7\r\n8 1\r\n']}, {'input': '10 10\r\nABBAABAABB\r\nABAAAAAABA\r\nBAABABABAA\r\nBAAAAAAAAB\r\nBABABBBAAB\r\nABBABBBBBA\r\nAABABAAAAA\r\nBAAAABAABA\r\nABABAABBAA\r\nBBABBABABB\r\n', 'output': ['9\r\n1 10\r\n']}, {'input': '10 11\r\nABBBAABABBB\r\nBBAABABBAAB\r\nAABBBBBAAAA\r\nBBABABAAABA\r\nAABABBBAABB\r\nAAABABAABAB\r\nBBABBBABBBB\r\nBBABABABBAA\r\nBBABABAAABB\r\nBABAABAABAB\r\n', 'output': ['5\r\n10 1\r\n']}, {'input': '12 11\r\nBBAAAABBAAB\r\nBBABBABBABB\r\nBAABABBABBA\r\nBABBBAAAABA\r\nABBAABBBBBA\r\nABBABBABABB\r\nAAABBBABBBB\r\nBAABAAABAAA\r\nAAAABBBBABA\r\nAAABAAABBBB\r\nBAAAAABABAB\r\nABBBBABABBB\r\n', 'output': ['7\r\n1 11\r\n']}, {'input': '12 13\r\nBBABABAAAAABA\r\nABAAAAAAAABBA\r\nABBBABAAAAABA\r\nBBBAABABBABBB\r\nABABAAABABABB\r\nABBAABAABBAAA\r\nAABABBAAABBAB\r\nABBBBBABBAABA\r\nBBBBBABBABBAA\r\nAAAAAAABBBAAB\r\nBAABBBAABAAAA\r\nBBBBBBABABABA\r\n', 'output': ['7\r\n12 1\r\n']}, {'input': '14 12\r\nBBAAABBBAAAB\r\nBBABAAAAABAA\r\nAABBABBBABBA\r\nBABAABAABBBB\r\nBBBABBBBABAA\r\nABBAABBAAABA\r\nABAAAAABBBAB\r\nBBAABBABBBAA\r\nBAABABAAABAB\r\nAAABBBABBABA\r\nBABBBBAABBBA\r\nAAAAABABBAAB\r\nBABBBABBBBBA\r\nBAAAABAABAAA\r\n', 'output': ['14\r\n1 12\r\n']}, {'input': '14 10\r\nABBAAABBAA\r\nBBBBBABBAA\r\nBABABBABAB\r\nAAABABBAAB\r\nBBABABBBAB\r\nBBABBABABB\r\nAABBBBABAA\r\nABBBAAAABB\r\nABBABAABAA\r\nABABABABBA\r\nABAABBBAAB\r\nAAAAAAAAAA\r\nABABBAABAA\r\nBABAABABBB\r\n', 'output': ['10\r\n1 10\r\n']}, {'input': '16 15\r\nABBBBAAABABBABB\r\nABBBAAABBABBBBB\r\nBABABAABBBABABB\r\nAAABBBBBABBABBB\r\nBAABAABAABAABBA\r\nABBBBAAAAAAAABB\r\nBAABBBABABAAAAB\r\nAAAABBAABBAABAA\r\nABBABABAAABABBB\r\nAAABBBABAABABAA\r\nBAABABBAAABBAAA\r\nAAAAAAABABBBAAA\r\nBABBAABBABAAAAB\r\nABABAAABBBBBAAB\r\nBBABBAABABAABBB\r\nBAAAABBBABABBBA\r\n', 'output': ['12\r\n4 3\r\n']}, {'input': '16 16\r\nABBABBABBAABBBAB\r\nBABABBAABAABBAAA\r\nBAAABBAABAABBBAA\r\nAABAAAABAAAABBBA\r\nBAAAABAABBBABBAA\r\nAABBABABABAABBBA\r\nBABBBABAAAAABABB\r\nBABBBBBBBBABBBAB\r\nBAAAABBBABAABBBA\r\nBABBBABBAABABBAA\r\nBBBBBBAABBBABBBA\r\nBABAAAABAABAABBB\r\nAAAAABBAAABABAAA\r\nBABBABABABAAABAB\r\nBAAAAAAAABBABAAA\r\nBAAAAABABBBBAAAA\r\n', 'output': ['15\r\n1 16\r\n']}, {'input': '18 18\r\nBBBBBBBABABBBABABA\r\nBAAABAAABBBABABBBB\r\nBABBAAABAAABAAABAA\r\nAABBABBBABBBBBAAAB\r\nBBBAAAAABBABBAAAAA\r\nAABBAABABABBBABABA\r\nBAABBAAAABABAABABB\r\nBABBABBBAAAABAABBA\r\nBBBBAABAAABAAABBBA\r\nABABBAAABBBBBABABA\r\nABABAABBBBBABBBBBB\r\nABAAABBABBABAAAABA\r\nBABAAABABABBBABBBB\r\nBBBBABBBABBBBBBBBA\r\nBAAABAABABABBBBAAB\r\nBABBAABABBABAABBBB\r\nBAABABAAAABBABBAAA\r\nBAAABBBAABABBABBAB\r\n', 'output': ['23\r\n2 6\r\n']}, {'input': '17 17\r\nBBAABAABBBBBAABBB\r\nBBABABBBBABAAABBB\r\nAAAABAAAABABABBAA\r\nBBABAAABBABBAAABA\r\nAAABBBBBAABABBBAB\r\nAABBBBBABABABABBB\r\nBAABAAABAAABBAABB\r\nBBAAAAAABABABBAAB\r\nAAAAABAABBAAAABAA\r\nBABAABABABABABBBB\r\nBAABABBAAABBAAABB\r\nABBAAABBBBAAAABAB\r\nBBABAABAAAAAABBBB\r\nAAABBABBAAAAABBBB\r\nAABAABBAABBABAABB\r\nABABAAABBABAAABAB\r\nBBABABBBAAAAAAABA\r\n', 'output': ['3\r\n1 17\r\n']}, {'input': '20 20\r\nABBBAAABABAAAAABBABB\r\nBABABBAABAABBAAABABB\r\nBABBBAABAABBABBBBABA\r\nBAAABBAAABABBABBAAAA\r\nABBAABAABBBBAAABBBAA\r\nBAAAAAAAABABBAAAAABB\r\nAAAAAAABABBBBBAABAAB\r\nABBBBABAABBAAAAABAAA\r\nBAAAAABBABAAAAABAAAB\r\nABABAABABBBABBAABBAA\r\nBAAABBBAAAABBBBBABAA\r\nAAABBABABAABBABAABAB\r\nABBABABABABAAABABABA\r\nBAABAAAAABBAABBBAAAB\r\nABAAABBABAABBBABAABA\r\nBAABBBBBABBBABBBABAB\r\nBABBABABBBBBBBBABAAA\r\nABAAABAAABAAABABABAA\r\nBAABBBBAABBAAAAAABBA\r\nABAABBABAAABBABABAAA\r\n', 'output': ['23\r\n1 10\r\n']}, {'input': '1 1\r\nC\r\n', 'output': ['1\r\n1 1\r\n']}, {'input': '2 2\r\nCC\r\nBB\r\n', 'output': ['2\r\n1 2\r\n']}, {'input': '3 3\r\nACA\r\nCCA\r\nACB\r\n', 'output': ['3\r\n1 3\r\n']}, {'input': '4 4\r\nACAC\r\nCBCC\r\nABBC\r\nCCAC\r\n', 'output': ['5\r\n1 4\r\n']}, {'input': '5 5\r\nBBCAB\r\nBCBAC\r\nCAAAB\r\nACBBA\r\nCAACB\r\n', 'output': ['3\r\n1 5\r\n']}, {'input': '14 16\r\nCBCCCABCBBBAAACC\r\nAABAACBACBCBACCA\r\nABBBABAACCACCCCC\r\nBBACACACCCCBBBAC\r\nBBCAABACBAACBCAA\r\nAAACCACBBCABABCB\r\nABCBCAAAAACBABBA\r\nAAABBBCCBAACBBCA\r\nBBAACBABBBCCBAAC\r\nBAABCCBAAABAACAC\r\nABBBBCBAACACCBCB\r\nBCABACBBBCAACACC\r\nACCCCABCCCBBCAAC\r\nBCBBCCCBCBCCACAA\r\n', 'output': ['15\r\n7 1\r\n']}, {'input': '16 16\r\nACABBCCBAABCCCCB\r\nAABCACCAAACACABB\r\nBCCCAABBAACBACAA\r\nBCACAABBBCAAAABA\r\nACCBABCCACABBCCC\r\nCCAAACACACBCABCA\r\nBCAACBBBCACBBCAB\r\nBABBCBBBCCCBAACC\r\nBBBBBABACBABBCBA\r\nABAACBACCACBBABA\r\nABAACBACCBCBCCBB\r\nBCACCCAABCBBCBCB\r\nBBBCCCBCCBCBACCA\r\nAABCBBBBACCACCBB\r\nBCABCCCBCBBBCBCC\r\nACCCCCCBBBAABACC\r\n', 'output': ['17\r\n4 2\r\n']}, {'input': '17 17\r\nBCBAAABAABCCCAAAC\r\nBBAABCABBAACCACBB\r\nABCCBAABBCCABBBAB\r\nAACCBBACCAAACCACA\r\nABBACBAAAABBABCAA\r\nACBACCCABAABBCABB\r\nCBCCCBCACBABCAAAA\r\nAAABACACABABCCCBC\r\nCABABBABBBABBBCAB\r\nBCBCBAAACCCACACBA\r\nBBACABACAAABCCBBC\r\nABAABBABCCAABBCCA\r\nAABBACBCBCCBAACBB\r\nBBABCBBCCCBCACBCB\r\nBABCBBCCABCABBAAA\r\nAABAABBBBAACAABCC\r\nBACCCBBCCABBBACBB\r\n', 'output': ['3\r\n1 17\r\n']}, {'input': '19 19\r\nACCACBCABACABCACCAA\r\nBCACAAAACCACCCCBCCB\r\nCBACBBCBCBCABCABACA\r\nAACCAABBBCAAABACAAC\r\nACACCCBBBACACCAAABA\r\nAACAABCACCBCACCABBA\r\nAABBCCABACCACABACAA\r\nACBCCACBACCACABCABC\r\nAACAABCAACCBBAACBCA\r\nAAACACBAABCBACCAAAB\r\nAABACABBABCACAACBCA\r\nBABAAABCACBABACBBBC\r\nBAABCAAABCAABBCCAAC\r\nBCABCCBCCBCBABCBCCA\r\nBACACBACBCABBCBCABB\r\nABCACCBBBBCBBCABAAC\r\nBBBBCCBCBACAACBCBCA\r\nAAABBBBCACCACCAAACC\r\nCCCCCBAABAAAACCCBBA\r\n', 'output': ['3\r\n1 19\r\n']}, {'input': '20 18\r\nAABCAACCBBCBABBBBB\r\nBBCBAACCBCAACBBCCB\r\nACCBABABACBBACBBAB\r\nACBBBCBAAACAAAAABB\r\nBCBABABAACCCABBBCC\r\nBAAAAAACACABBCCCAC\r\nCBACCBCBACACAAACBC\r\nCBACAACBCBCAACACCA\r\nCCCBACCBACACCCBCCB\r\nCACABBBBBBCCBACCBA\r\nCCBCACABCBACABBCCB\r\nAACACCCCCABAABCACC\r\nCBBACCBBCBCBBCCAAB\r\nCABBABACCABACAABAB\r\nBBBABBCBCBACBCCABA\r\nBCCAACBCBCAAAABACA\r\nAAABACBBCCCACACBAC\r\nBABAAAACCBACBACAAA\r\nAABBABCBBBACAACBAB\r\nBBABBAABACBAABCCBB\r\n', 'output': ['27\r\n4 2\r\n']}, {'input': '1 1\r\nZ\r\n', 'output': ['1\r\n1 1\r\n']}, {'input': '2 2\r\nML\r\nWQ\r\n', 'output': ['4\r\n1 1\r\n']}, {'input': '3 3\r\nBXP\r\nUJF\r\nAQT\r\n', 'output': ['4\r\n1 1\r\n']}, {'input': '4 3\r\nOKJ\r\nXTV\r\nDVW\r\nHMK\r\n', 'output': ['5\r\n2 1\r\n']}, {'input': '5 5\r\nDZEZF\r\nOHZZC\r\nCNDOX\r\nNVYDP\r\nUCIAX\r\n', 'output': ['3\r\n1 5\r\n']}, {'input': '6 6\r\nQLXBOE\r\nKEEYTR\r\nZLPMSP\r\nWOKAHN\r\nLYXBXU\r\nSZOEZV\r\n', 'output': ['14\r\n2 1\r\n']}, {'input': '6 7\r\nGYSGYUL\r\nKGTJUVI\r\nFNRHOND\r\nZGZAFYZ\r\nQVCRZCA\r\nJCCXKGV\r\n', 'output': ['7\r\n2 1\r\n']}, {'input': '8 8\r\nTNMIIMOP\r\nJOAXSHVN\r\nQYHMVXGM\r\nQOXAIUMI\r\nLAAXNKCH\r\nORWESZUV\r\nPMIXHLEA\r\nAENPGVYK\r\n', 'output': ['13\r\n1 4\r\n']}, {'input': '9 9\r\nIZHKRCRTM\r\nLQBOENMNQ\r\nYLNVFBFUY\r\nACTTYWABL\r\nYSEGWNQHC\r\nTZASWPPAG\r\nLLZTKFPMV\r\nGXBETPPPN\r\nUCPEFNJKN\r\n', 'output': ['8\r\n1 3\r\n']}, {'input': '9 10\r\nXHPCDAAFPZ\r\nJRZCDTQBYP\r\nZBTAMDPIFY\r\nXBKTMXNIWM\r\nDAIONPEBYF\r\nAFHBCBDTKB\r\nKRVEBSUXRM\r\nWGMEZTWDBX\r\nNOJUCDZPZY\r\n', 'output': ['10\r\n3 1\r\n']}, {'input': '12 13\r\nTHSGJEPTDFEIJ\r\nOWPJGXSXJRYGD\r\nVYENWXFWSOSMX\r\nFZDFXFPWEIYYV\r\nOEODFOGQWJEEU\r\nSQRNSBTAMLQRU\r\nLXGZERSWTJWQK\r\nLGRJJMDTZVZWJ\r\nDWVBTSZKFUAHT\r\nHSSZHXAWVWMHB\r\nJZOCNFUHTHQYV\r\nTUHDMTZAQVWDL\r\n', 'output': ['10\r\n3 1\r\n']}, {'input': '14 13\r\nBGBALYLHQYMFM\r\nRLFOZFDFMRFEN\r\nGDWROOMXUVBOW\r\nDPXWRDPCEFMRQ\r\nJOSEGKGMHGHFC\r\nJHXUBTPOZOYGJ\r\nFHUUMHWSQRNEP\r\nVGWYMTMWHWGIL\r\nVMWDTBDJGEVZI\r\nLEJSIHTQKYDXY\r\nOLUOIWECMZVAI\r\nVDXSGRPMCCJEM\r\nMYWMDDAQAPBSG\r\nXQWPFRAPVEOYO\r\n', 'output': ['6\r\n7 1\r\n']}, {'input': '14 15\r\nJFLSOQHVDRTCPWZ\r\nWSROLOOQOCWPJNX\r\nEEUZVBLQXBFQKNA\r\nQIGZDIMDXVCHJFJ\r\nUDJGIZWDBMMMBJR\r\nEWXAQHPRYBQOYDT\r\nUDEAPOBVZOXNVMK\r\nAYEVKFIKNRUVRQC\r\nNLTLJBXWMUQXAZD\r\nKOXESBBUYLMIDOI\r\nZOJWEOJFCYTILHE\r\nRQDNTBZZXPKNCEN\r\nSYGFASAQUSMYYRP\r\nUOYCFYUDACJDTAD\r\n', 'output': ['13\r\n1 5\r\n']}, {'input': '16 15\r\nPFUMRKDISIBBVYP\r\nMZKXWWSQXADAPEB\r\nVTBYXGWQYZTHBHY\r\nONGURZKWHZDKIDF\r\nGCMHQQNJJXHHPVU\r\nNLMUXXKZOFNMFTG\r\nANDDDPHEDVWVHLC\r\nOYGXUHIMYPNIXCT\r\nILCGDQZNCSTIILX\r\nZVSYMJBHAUEXZMY\r\nMYOKFPJKKJLKVWI\r\nUEMUOOAJSNTOLEN\r\nLKIROZUNWRZBMZP\r\nYYWCXLGHLZQVPOB\r\nFMHPKABCBAAYCFA\r\nNRGFEWPLKNORSZR\r\n', 'output': ['18\r\n1 3\r\n']}, {'input': '14 17\r\nXGFETCAWEBHYYDECE\r\nCGFEUQEYMLSVHNKJA\r\nZMGSXZJASBUPTHRFQ\r\nGQREDKHDBTZPGWHEO\r\nQGACDHZVBAOGLHHEL\r\nLKLKVFVDHSRQNEDXC\r\nVNREYHZDJHPJKHXDO\r\nKBOMZYHZEUOYUOXSQ\r\nFNQGOBVDBTMUJPAKU\r\nXFPGQQXBPELKWSXCJ\r\nABUKLBPTFOGUJFDEQ\r\nKXPJEZJQCHTENYSKY\r\nXXOKEXESEVLQMFDZG\r\nVPGUBSJLGBWZWAMFZ\r\n', 'output': ['6\r\n7 1\r\n']}, {'input': '16 17\r\nFFOYWWWJRUPVBGSSJ\r\nVPOMWQMWUWYMMDAPB\r\nARQUYXZTHVSQZHMVJ\r\nCJAGELECYEXSHEYTU\r\nXRSZPRCBQPJQACNWR\r\nJISALKDCKJUWWHMYH\r\nGMISALZMLGRRGALJA\r\nCWPYTQYBXKLBGWKNF\r\nMJJYWBIHJLARHFNWB\r\nKEREXXISTPANXGGJG\r\nLECEJLPAFOZHLRTJM\r\nHBOWFNSQFRRGEJFMJ\r\nVEGIRVEXACMJVKFYN\r\nSCGOPQKUHEDNIPIRE\r\nLENRPPYJBEVDTOPOY\r\nFHJOESUHLIJRFPVBK\r\n', 'output': ['8\r\n4 1\r\n']}, {'input': '18 19\r\nLEXQWPUXGOWSELHIQPY\r\nZUYPTUDHEEQVRWBCXBU\r\nZUPMYQQQFHGKZZDMLFM\r\nCASSUVIKQKCEALUDDFK\r\nFDBZOXULVGFARYPNAQY\r\nWEFLTZOSOAGAMBWNGVC\r\nEVAPNTSSIMKNBOAHFSC\r\nUHTWEBRCEUJSARNEWYI\r\nGXGSDCDUIWYQRZUPQBZ\r\nFMYJUOHENURMDINJGCN\r\nHIBATJCOGWWRQWTLXDH\r\nRDDXJNZHQGUWPNGIDRO\r\nAJGHDUCGGLPYYDYSFRS\r\nAZGBVLJYYZWSQGBFJVU\r\nQJJRSHZFOECHGRGALML\r\nJKDMLPREFTISSSAJKJN\r\nGRHGVYSVQLYKCIMBIKA\r\nMSHRBZJJLDHBCAWAJBN\r\n', 'output': ['10\r\n3 1\r\n']}, {'input': '20 18\r\nNLBILWYVJJLCACSMUA\r\nAAMAWVGEZDTWUUZNMM\r\nWWNOTPPFXJSWWSPPRB\r\nYUJXZSHHNFGKXIXEJN\r\nLTKNJOJALEQURSYVBI\r\nSVXHFTUYWTLBXWFDXD\r\nLQUEBPXELRNAXFIKFT\r\nZGZEPWGVLVNMQVRMJM\r\nWTMIPWRNQCWKZACSKQ\r\nYGUREEGHTVMICOCUHE\r\nUNIJGNPINIFWCIHGIQ\r\nIRGJEHFRUJOHIXRSLF\r\nDQVCPHUSKYEHFGWBPS\r\nJIIGNJKTRAAPRBOGMQ\r\nHFNGDLVBUVECUMQDMT\r\nGEGCSOPRXQAEMDQAYO\r\nOHSBTADOWBVKZINKXC\r\nIIPWCAZSNDFVBMTGMI\r\nOZZTLUOFRYDNTPIAVA\r\nTFBGPAMJPIWLEZOKXB\r\n', 'output': ['33\r\n1 3\r\n']}, {'input': '2 4\r\nABAA\r\nABBB\r\n', 'output': ['2\r\n1 4\r\n']}, {'input': '6 6\r\nCCABCA\r\nBCBCBC\r\nBAAAAA\r\nCBBCAA\r\nACBBCA\r\nCCAABA\r\n', 'output': ['10\r\n1 6\r\n']}, {'input': '16 4\r\nBAAC\r\nBACA\r\nACBC\r\nABCC\r\nCCAC\r\nBBCC\r\nCCAB\r\nABCC\r\nCBCA\r\nBCBC\r\nBCBC\r\nCBBB\r\nBBAA\r\nBACA\r\nABCB\r\nAABA\r\n', 'output': ['9\r\n2 4\r\n']}, {'input': '2 14\r\nAABACBACBCBBCB\r\nBACCBBBCBAABBC\r\n', 'output': ['4\r\n1 7\r\n']}, {'input': '4 8\r\nCACABCCA\r\nABCBAACA\r\nACABBBCC\r\nAACCBCBB\r\n', 'output': ['8\r\n1 4\r\n']}, {'input': '12 18\r\nCBBCAACABACCACABBC\r\nABCAACABAABCBCBCCC\r\nBCAACCCBBBABBACBBA\r\nACCBCBBBAABACCACCC\r\nCAABCCCACACCBACACC\r\nBBBCBCACCABCCBCBBB\r\nBAABBCACAAAAACCBCB\r\nBAABAABACBCABACBCA\r\nAABCBCCBCCABACCCAC\r\nCCBBBAACCCBCACCCBB\r\nCBABACBBBABCBACCCB\r\nAABACCCBCCACBCACCB\r\n', 'output': ['24\r\n4 2\r\n']}]


Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of N lines and M columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief.Scientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way.

The first line contains two integers N and M (1 ≤ N, M ≤ 50) — the number of lines and columns on the slab. The next N lines contain M symbols each — the final coloration of the slab. W stands for the square that should be painted white and B — for the square that should be painted black.

In the single line output the minimal number of repaintings of side-linked areas needed to get the required coloration of the slab.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.ArrayDeque;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        final int INF = 0x3f3f3f3f;
        String[] matrix;
        int[][] zoneIndex;
        int zones;
        int[] dx = new int[]{-1, 0, 1, 0};
        int[] dy = new int[]{0, 1, 0, -1};
        int blackNodes;
        List<Integer>[] graph;

        @SuppressWarnings("unchecked")
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt(), m = in.nextInt();
            matrix = new String[n];
            for (int i = 0; i < n; ++i)
                matrix[i] = in.next();

            zoneIndex = new int[n][m];
            for (int[] p : zoneIndex) Arrays.fill(p, -1);
            zones = 0;
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    if (matrix[i].charAt(j) == 'B' && zoneIndex[i][j] == -1) {
                        dfs(i, j);
                        zones++;
                    }
                }
            }
            blackNodes = zones;
            if (zones <= 1) {
                out.println(zones);
                return;
            }
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    if (matrix[i].charAt(j) == 'W' && zoneIndex[i][j] == -1) {
                        dfs(i, j);
                        zones++;
                    }
                }
            }

            graph = new List[zones];
            for (int i = 0; i < zones; ++i)
                graph[i] = new ArrayList<>();
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    getEdges(i, j);
                }
            }
            for (int i = 0; i < zones; ++i) {
                Collections.sort(graph[i]);
                List<Integer> adj = new ArrayList<>();
                int prev = -1;
                for (int p : graph[i]) {
                    if (p != prev) {
                        adj.add(p);
                        prev = p;
                    }
                }
                graph[i] = adj;
            }

            Queue<Integer> q = new ArrayDeque<>();
            int ans = INF;
            for (int i = 0; i < zones; ++i) {
                int[] dist = new int[zones];
                dist[i] = 1;
                q.add(i);
                int mdist = 1;
                while (!q.isEmpty()) {
                    int node = q.poll();
                    mdist = dist[node];
                    for (int p : graph[node]) {
                        if (dist[p] == 0) {
                            dist[p] = dist[node] + 1;
                            q.add(p);
                        }
                    }
                }
                if (i >= blackNodes) mdist &= ~1;
                else mdist -= (mdist & 1) ^ 1;
                ans = Math.min(ans, mdist);
            }

            out.println(ans);
        }

        private void dfs(int x, int y) {
            zoneIndex[x][y] = zones;
            for (int k = 0; k < 4; ++k) {
                int nx = x + dx[k], ny = y + dy[k];
                if (0 <= nx && nx < matrix.length &&
                        0 <= ny && ny < matrix[0].length() &&
                        matrix[x].charAt(y) == matrix[nx].charAt(ny) &&
                        zoneIndex[nx][ny] == -1) {
                    dfs(nx, ny);
                }
            }
        }

        private void getEdges(int x, int y) {
            int node = zoneIndex[x][y];
            for (int k = 0; k < 4; ++k) {
                int nx = x + dx[k], ny = y + dy[k];
                if (!(0 <= nx && nx < matrix.length &&
                        0 <= ny && ny < matrix[0].length())) continue;
                int p = zoneIndex[nx][ny];
                if (p != node) {
                    graph[node].add(p);
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new UnknownError();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new UnknownError();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

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

        public String next() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuffer res = new StringBuffer();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));

            return res.toString();
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}


Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.

The first line contains one integer N (1 ≤ N ≤ 1000) — the number of words in Old Berland language. The second line contains N space-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000.

If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.

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

public class Main {

  static class Pair implements Comparable<Pair> {
    public Integer first;
    public Integer second;
    public Pair(Integer first, Integer second) {
      this.first = first;
      this.second = second;
    }
    @Override
    public int compareTo(Pair other) {
      return this.first.compareTo(other.first);
    }
  }

  static class Node {
    public int isBlock = 0;
    public Node[] child;
    public Node pre;
    public Node() {
      this.isBlock = 0;
      this.pre = null;
      this.child = new Node[2];
      Arrays.fill(child, null);
    }
  }

  private static int maxn = 1000001;
  private static int MAX = 2;
  private static String[] ans = new String[10001];
  private static String s;

  private static Node root = new Node();

  private static boolean add(int l) {
    Node temp = root;
    if (root.isBlock == 1)
      return false;
    s = "";
    for (int i = 0; i < l; i++) {
      int check_l = -1;
      boolean canmove = false;
      for (int j = MAX - 1; j >= 0; j--) {
        if (temp.child[j] != null) {
          if (temp.child[j].isBlock == 0) {
            s = s + (char) ('0' + j);
            temp = temp.child[j];
            canmove = true;
            break;
          }
        }
        if (temp.child[j] == null)
          check_l = j;
      }

      if (!canmove) {
        if (check_l == -1)
          return false;
        else {
          s = s + (char) ('0' + check_l);
          temp.child[check_l] = new Node();
          temp.child[check_l].pre = temp;
          temp = temp.child[check_l];
        }
      }
    }

    temp.isBlock = 1;

    while (temp != null) {
      if (temp.child[0] != null && temp.child[1] != null)
        if (temp.child[0].isBlock * temp.child[1].isBlock == 1)
          temp.isBlock = 1;
      temp = temp.pre;
    }

    return true;

  }

  public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      Pair[] a = new Pair[n + 1];
      for (int i = 0; i < n; i++) {
        int l = sc.nextInt();
        a[i] = new Pair(l, i);
      }

      Arrays.sort(a, 0, n);

      for (int i = 0; i < n; i++) {
        int l = a[i].first;
        if (add(l) == false) {
          System.out.println("NO");
          return;
        }
        else
          ans[a[i].second] = s;
      }

      System.out.println("YES");
      for (int i = 0; i < n; i++)
        System.out.println(ans[i]);

      sc.close();

  }

}


Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di — the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.

The first line contains integer A (1 ≤ A < 10300). It is guaranteed that the number doesn't contain leading zeros.

On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO.  If the answer is YES, then you also have to print number k — the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers — a1, a2, ..., ak. Those numbers have to be output in the increasing order. On the next line you should output number p — how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number — the sought number of residents. Those number also have to go in the increasing order.  If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Main {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BigInteger A = new BigInteger(bf.readLine().trim());
		List<BigInteger> pow = new ArrayList<BigInteger>();
		pow.add(BigInteger.ONE);
		BigInteger twl = new BigInteger("12");
		for (int i=1; i<600; i++) {
			pow.add(pow.get(i-1).multiply(twl));
		}
		int n = -1;
		for (int i=0;i<600;i++) {
			for (int j=0;j<=i/2;j++) {
				if (pow.get(j).add(pow.get(i-j)).compareTo(A) == 0) {
					n = i;
					break;
				}
			}
		}
		if (n == -1) {
			System.out.println("NO");
		} else {
			System.out.printf("YES\n1\n%d\n%d\n", n + 1, n/2);

			for (int j=n/2; j>=0; j--) {
				if (pow.get(j).add(pow.get(n-j)).compareTo(A) != 0) {
					System.out.println(pow.get(j).add(pow.get(n-j)));
				}
			}
		}
	}

}


Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could  open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);  move freely from a room to a room if a corresponding door is open;  give keys to one another, being in one room.  "Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.

The first line contains three preset integers n, m и k (1 ≤ n, m, k ≤ 1000) — the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space — the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.

Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".

2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0

4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class Rooms implements Runnable {
    static class Door {
        int a;
        int b;
    }

    static class Component {
        Set<String> names = new HashSet<String>();
        Set<Door> keys = new HashSet<Door>();

        public int size() {
            return names.size() + keys.size();
        }
    }

    private void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        int k = nextInt();
        Door[] door = new Door[m];
        for (int i = 0; i < m; ++i) {
            door[i] = new Door();
            door[i].a = nextInt() - 1;
            door[i].b = nextInt() - 1;
        }
        Component[][] res = new Component[2][];
        for (int step = 0; step < 2; ++step) {
            Component[] where = new Component[n];
            for (int i = 0; i < n; ++i) {
                where[i] = new Component();
            }
            for (int i = 0; i < k; ++i) {
                String name = nextToken();
                int room = nextInt() - 1;
                Component cur = where[room];
                cur.names.add(name);
                int cnt = nextInt();
                for (int j = 0; j < cnt; ++j) {
                    cur.keys.add(door[nextInt() - 1]);
                }
            }
            while (true) {
                boolean changed = false;
                for (Door d : door) {
                    if (where[d.a] == where[d.b])
                        continue;
                    if (where[d.a].keys.contains(d) || where[d.b].keys.contains(d)) {
                        changed = true;
                        Component a = where[d.a];
                        Component b = where[d.b];
                        a.keys.addAll(b.keys);
                        a.names.addAll(b.names);
                        for (int i = 0; i < n; ++i)
                            if (where[i] == b)
                                where[i] = a;
                    }
                }
                if (!changed)
                    break;
            }
            res[step] = where;
        }
        boolean result = true;
        for (int i = 0; i < n; ++i) {
            Component a = res[0][i];
            Component b = res[1][i];
            if (a.names.equals(b.names) && a.keys.equals(b.keys))
                continue;
            result = false;
            break;
        }
        if (result)
            writer.println("YES");
        else
            writer.println("NO");

    }

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

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }
}


In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not.    Figure 1     Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.

The first line of the test case will consist of the number of vertices n (3 ≤ n ≤ 1000). Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≤ xi, yi ≤ 106) separated by a space. The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2).

Output consists of a single line containing the number of points where the watchtower can be set up.

NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0.

import java.util.Scanner;

public class CF67E {
	static int[] x, y;

	static long cross(int i, int j, int k) {
		long x1=x[j] - x[i];
		long x2=x[k] - x[i];
		long y1=y[j] - y[i];
		long y2=y[k] - y[i];
		return x1 * y2 - x2 * y1;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		x = new int[n];
		y = new int[n];
		for (int i = 0; i < n; i++) {
			x[i] = sc.nextInt();
			y[i] = sc.nextInt();
		}

		boolean flip = x[0] < x[1];
		int X = x[1], Y = y[1];
		for (int i = 0; i < n; i++) {
			x[i] -= X;
			y[i] -= Y;
			if (flip) {
				x[i] = -x[i];
				y[i] = -y[i];
			}
		}

		int l = 0, r = x[0];
		for (int i = 2; i + 1 < n; i++) {
			long cr = cross(i, i + 1, 0);
			long cl = cross(i, i + 1, 1);
			if (cr > 0 && cl > 0) {
				System.out.println(0);
				return;
			}
			int x0 = x[i], y0 = y[i], x1 = x[i + 1], y1 = y[i + 1];
			if (cr > 0 || cl > 0) {
				long p = (long) x0 * (y1 - y0) - (long) y0 * (x1 - x0);
				long q = y1 - y0;
				if (q < 0) {
					p = -p; q = -q;
				}
				if (cr > 0)
					r = Math.min(r, (int) (p / q));
				else
					l = Math.max(l, (int) ((p + q - 1) / q));
			}
		}
		System.out.println(l <= r ? r - l + 1 : 0);

	}
}


Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules:  On the checkered paper a coordinate system is drawn. A dot is initially put in the position (x, y).  A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line y = x.  Anton and Dasha take turns. Anton goes first.  The player after whose move the distance from the dot to the coordinates' origin exceeds d, loses. Help them to determine the winner.

The first line of the input file contains 4 integers x, y, n, d ( - 200 ≤ x, y ≤ 200, 1 ≤ d ≤ 200, 1 ≤ n ≤ 20) — the initial coordinates of the dot, the distance d and the number of vectors. It is guaranteed that the initial dot is at the distance less than d from the origin of the coordinates. The following n lines each contain two non-negative numbers xi and yi (0 ≤ xi, yi ≤ 200) — the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different.

You should print "Anton", if the winner is Anton in case of both players play the game optimally, and "Dasha" otherwise.

NoteIn the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move — to reflect relatively to the line y = x. Dasha will respond to it with the same move and return the dot in position (2;3).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Dot {

    static int N, D;
    static int[] vx, vy;
    static Boolean[][][][] dp;

    static long sq(long x) {
	return x * x;
    }

    static boolean solve(int p1, int p2, int x, int y) {
	if (sq(x) + sq(y) > sq(D))
	    return true;
	if (dp[p1][p2][x + 200][y + 200] != null)
	    return dp[p1][p2][x + 200][y + 200];
	boolean ans = false;
	if (p1 == 0)
	    ans |= !solve(p2, 1, y, x);
	for (int i = 0; i < N; i++)
	    ans |= !solve(p2, p1, x + vx[i], y + vy[i]);
	return dp[p1][p2][x + 200][y + 200] = ans;
    }

    public static void main(String[] args) throws IOException {
	MyScanner sc = new MyScanner(System.in);
	PrintWriter out = new PrintWriter(System.out);
	int x = sc.nextInt(), y = sc.nextInt();
	N = sc.nextInt();
	D = sc.nextInt();
	vx = new int[N];
	vy = new int[N];
	for (int i = 0; i < N; i++) {
	    vx[i] = sc.nextInt();
	    vy[i] = sc.nextInt();
	}
	dp = new Boolean[2][2][402][402];
	out.println(solve(0, 0, x, y) ? "Anton" : "Dasha");
	out.flush();
	out.close();
    }

    static class MyScanner {

	BufferedReader br;
	StringTokenizer st;

	MyScanner(InputStream is) {
	    br = new BufferedReader(new InputStreamReader(is));
	}

	String next() throws IOException {
	    while (st == null || !st.hasMoreTokens())
		st = new StringTokenizer(br.readLine());
	    return st.nextToken();
	}

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

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

	boolean ready() throws IOException {
	    return br.ready();
	}
    }
}


Once a walrus professor Plato asked his programming students to perform the following practical task. The students had to implement such a data structure that would support a convex hull on some set of points S. The input to the program had q queries of two types: 1. Add a point with coordinates (x, y) into the set S. Note that in this case the convex hull of S could have changed, and could have remained the same. 2. Say whether a point with coordinates (x, y) belongs to an area limited by the convex hull, including the border. All the students coped with the task. What about you?

The first line contains an integer q (4 ≤ q ≤ 105).  Then follow q lines in the following way: "t x y", where t is the query type (1 or 2), and (x, y) are the coordinates of the point ( - 106 ≤ x, y ≤ 106, x and y are integers).  There is at least one query of type 2. It is guaranteed that the three queries of the first type follow first and the points given in the queries form a non-degenerative triangle. Also all the points added in S are distinct.

For each query of the second type print one string containing "YES", if the point lies inside the convex hull or on its border. Otherwise, print "NO".

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class ConvexHull {

    static class Point{
        int x;
        int y;
        Point(int x, int y){
            this.x = x;
            this.y = y;
        }
    }

    static long cross(Point a, Point b, Point c){
       return (long) (b.x - a.x) * (c.y - a.y) - (long) (b.y - a.y)*(c.x - a.x);
    }

    static boolean isItOut(Point a, Point b, Point c, boolean upper){
        if(a == null || b == null) {
            return true;
        }
        if(upper && (a == b && a.y < c.y || cross(a,b,c) > 0)){
            return true;
        }
        if(!upper && (a == b && a.y > c.y || cross(a,b,c) < 0)){
            return true;
        }
        return false;
    }

    static void removePoint(TreeSet<Point> t, Point p, boolean right, boolean upper){
        Point a = right ? t.ceiling(p) : t.floor(p);
        if(a == null){
            return;
        }
        if(a.x == p.x){
            t.remove(a);
            a = right ? t.ceiling(p) : t.floor(p);
        }
        if(a == null){
            return;
        }
        Point b = right ? t.higher(a) : t.lower(a);
        int sign = upper ? 1 : -1;
        sign = right ? sign * 1 : sign * -1;
        while(b != null && cross(p, a, b) * sign >= 0){

            t.remove(a);
            a = b;
            b = right ? t.higher(a) : t.lower(a);

        }
    }

    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int q = Integer.parseInt(br.readLine());
        //upper hull
        TreeSet<Point> upper = new TreeSet<>((a,b) -> a.x - b.x);
        //lower hull
        TreeSet<Point> lower = new TreeSet<>((a,b) -> a.x - b.x);

        while(q > 0){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int t = Integer.parseInt(st.nextToken());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            Point p = new Point(x,y);
            Point ul = upper.floor(p);
            Point ur = upper.ceiling(p);
            Point ll = lower.floor(p);
            Point lr = lower.ceiling(p);

            boolean outupper = isItOut(ul, ur, p, true);
            boolean outlower = isItOut(ll, lr, p, false);

            if(t == 1){
                //add to convex hull
                if(outupper){
                    removePoint(upper, p, true, true);
                    removePoint(upper, p, false, true);
                    upper.add(p);
                }
                if(outlower){
                    removePoint(lower, p, true, false);
                    removePoint(lower, p, false, false);
                    lower.add(p);
                }

            }else{
                //see if in convex hull
                //is it right or left?
                System.out.println(outupper || outlower ? "NO" : "YES");
                //above top curve

                //below bottom curve

            }
            //Point[] up = upper.toArray();
            //System.out.printf("UPPER:  ");
            //for(int i = 0; i < up.length; i ++){
            //    System.out.printf("%d %d   ", up[i].x, up[i].y);
            //}

            //Object[] low = lower.toArray();
            //System.out.printf("\nLOWER:  ");
            //for(int i = 0; i < low.length; i ++){
            //    System.out.printf("%d %d   ", low[i].x, low[i].y);
            //}
            //System.out.println();

            q--;
        }

    }

}


Vasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces. Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than k tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.

The first line contains three integers n, m and k (1 ≤ n, k ≤ 106, 0 ≤ m ≤ 106). Each of the next m lines contains two integers. They are the numbers of cities connected by a corresponding road. No road connects city to itself and there is at most one road between each pair of cities.

Print a single number, the minimum number of additional roads.

NoteIn the first example only one province exists, so it is not necessary to build any tunnels or roads.In the second example two provinces exist. It is possible to merge the provinces by building a tunnel between cities 1 and 3.In the third example at least one additional road is necessary. For example it is possible to build additional road between cities 1 and 2 and build two tunnels between cities 1 and 3, 2 and 4 after that.

import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.Collections;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author AlexFetisov
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.nextInt();
        int m = in.nextInt();
        int k = in.nextInt();
        DisjointSet dsu = new DisjointSet(n);
        int[] size = new int[n];
        Arrays.fill(size, 1);
        while (m-- > 0) {
            int a = in.nextInt() - 1;
            int b = in.nextInt() - 1;
            int newSize = size[dsu.findSet(a)] + size[dsu.findSet(b)];
            if (dsu.union(a, b)) {
                int newRep = dsu.findSet(a);
                size[newRep] = newSize;
            }
        }
        List<Integer> componentSizes = new LinkedList<Integer>();
        boolean[] u = new boolean[n];
        for (int i = 0; i < n; ++i) {
            int rep = dsu.findSet(i);
            if (!u[rep]) {
                u[rep] = true;
                componentSizes.add(Math.min(size[rep], k));
            }
        }
        if (k == 1) {
            out.println(Math.max(0, componentSizes.size() - 2));
            return;
        }

        Collections.sort(componentSizes);
        int singleComponent = 0;
        while (!componentSizes.isEmpty() && componentSizes.get(0) == 1) {
            ++singleComponent;
            componentSizes.remove(0);
        }
        int freeLinks = 0;
        int edges = 0;
        for (int sz : componentSizes) {
            if (edges < 2) {
                freeLinks += sz - 1;
            } else {
                freeLinks += sz - 2;
            }
            ++edges;
        }
        if (singleComponent == 0) {
            out.println(0);
            return;
        }
        if (edges == 0) {
            singleComponent = (singleComponent + 1) / 2;
            out.println(singleComponent-1);
            return;
        }
        if (edges == 1) {
            ++freeLinks;
        }
        if (singleComponent <= freeLinks) {
            out.println(0);
        } else {
            singleComponent -= freeLinks;
            singleComponent = (singleComponent + 1) / 2;
            out.println(singleComponent);
        }
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer stt;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
    }

    public String nextLine() {
        try {
            return reader.readLine().trim();
        } catch (IOException e) {
            return null;
        }
    }

    public String nextString() {
        while (stt == null || !stt.hasMoreTokens()) {
            stt = new StringTokenizer(nextLine());
        }
        return stt.nextToken();
    }

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

}

class DisjointSet {
    int[] parent;
    int[] rank;

    public DisjointSet(int size) {
        parent = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; ++i) {
            parent[i] = i;
            rank[i] = 0;
        }
    }

    public int findSet(int x) {
        if (parent[x] != x) {
            parent[x] = findSet(parent[x]);
        }
        return parent[x];
    }

    public boolean union(int x, int y) {
        x = findSet(x);
        y = findSet(y);
        if (x != y) {
            if (rank[x] < rank[y]) {
                parent[x] = y;
            } else {
                parent[y] = x;
                if (rank[x] == rank[y]) {
                    ++rank[x];
                }
            }
            return true;
        }
        return false;
    }
}


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

d=set()
m=0
for _ in range(int(input())):
	x,i=input().split()
	if x=="-":
		if i in d:d.remove(i)
		else:m+=1
	else:
	  d.add(i)
	m=max(m,len(d))
print(m)


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

#http://codeforces.com/problemset/problem/722/A

time_format = int(raw_input())
time = raw_input().split(":")

hour = time[0]
minutes = time[1]

if (time_format == 12):
    if (int(hour) > 12):
        if (hour[1] == "0"):
            hour = "10"
        else:
            hour = "0" + hour[1]
    if (hour == "00"):
        hour = "01"
else:
    if (int(hour) > 23):
        hour = "0" + hour[1]

if (int(minutes) > 59):
    minutes = "0" + minutes[1]

print hour + ":" + minutes


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

n = int(input())
s = input()
s = list(s)
v = 0
while(True):
    lExits = False
    rExits = False
    if ('L' in s):
        l = s.index('L')
        lExits = True
    if ('R' in s):
        r = s.index('R')
        rExits = True
    if (lExits == False and rExits == False):
        break
    if (lExits == True and rExits == False):
        for i in range(l+1):
            s[i] = 'F'
        break
    if (lExits == False and rExits == True):
        for i in range(r,n):
            s[i] = 'F'
        break
    if (lExits == True and rExits == True):
        if (l < r):
            for i in range(l+1):
                s[i] = 'F'
        else:
            for i in range(r,l+1):
                s[i] = 'F'
            if ((l - r) % 2 == 0):
                s[r] = '.'
c = 0
for i in s:
    if (i == '.'):
        c += 1
print(c)


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

# prob B

n = input()
seq = raw_input()

seq = [int(i) for i in seq.split()]
seq.sort()

tot = 0
right_seq = range(1, n+1)
for num in seq:
    if num in right_seq:
        right_seq.remove(num)
    else:
        tot += 1

print tot


Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x + y = n).  The sizes of teams differ in no more than one (|x - y| ≤ 1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

n = int(input())
a = list(map(int, input().split()))
all = []
for i in range(n):
    all.append([a[i], i + 1])

all.sort(key = lambda x: x[0])

team_1 = []
team_2 = []
for i in range(n):
    if i % 2 == 0:
        team_1.append(all[i][1])
    else:
        team_2.append(all[i][1])

print(len(team_1))
print(*team_1)
print(len(team_2))
print(*team_2)