import java.util.Scanner;
public class Ishu
{
    	public static void main(String[] args)
    	{
	 Scanner scan=new Scanner(System.in);
	 int n,t,i,sum=0;
	 float l,r;
	 int[][] a=new int[2][1000];
	 n=scan.nextInt();
	 t=scan.nextInt();
	 for(i=0;i<n;++i)
		{
		 a[0][i]=scan.nextInt();
	 	 a[1][i]=scan.nextInt();
		}
	 for(i=1;i<n;++i)
		{
		 r=(float)a[0][i]-(float)a[1][i]/2;
		 l=(float)a[0][i-1]+(float)a[1][i-1]/2;
		 if(r-l==(float)t)
			++sum;
		 else if(r-l>(float)t)
			sum+=2;
		}
	 System.out.println((sum+2));
 	}
}

A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

import java.util.*;

public class Trying
{
    public static void main (String[] args)
    {
        Scanner enter = new Scanner(System.in);
        int n = enter.nextInt(), t = enter.nextInt(), pos = 0;
        double available[] = new double[n*2], xa[][] = new double [n][2],
        max = 0;
        for(int i = 0 ; i < n ; i++)
            for(int j = 0 ; j < 2 ; j++)
                xa[i][j] = enter.nextInt();
        max = 1 ;
        while(max != 1001)
        {
            max = 1001;
            for(int i = 0 ; i < n-1 ; i++)
            {
                if(xa[i][0] > xa[i+1][0])
                {
                    max = xa[i][0];
                    xa[i][0] = xa[i+1][0];
                    xa[i+1][0] = max ;
                    max = xa[i][1];
                    xa[i][1] = xa[i+1][1];
                    xa[i+1][1] = max ;
                }
            }
        }
        for(int i = 0 ; i < n ; i++)
        {
            available[pos] = xa[i][0] - xa[i][1]/2;
            pos++;
            available[pos] = xa[i][1]/2 + xa[i][0];
            pos++;
        }
        max = 0;
        for(int i = 1 ; i <= 2*n-2 ; i+=2)
        {
            if(available[i+1] - available[i] > t)
                max+=2;
            else if(available[i+1] - available[i] == t)
                max++;
        }
        System.out.println((int)max+2);
    }
}


import java.util.Scanner;
public class Ishu
{
    	public static void main(String[] args)
    	{
	 Scanner scan=new Scanner(System.in);
	 int i,j,flag=0;
	 String s1,s2,s3;
	 char[] ch=new char[100000];
	 char[] ch1=new char[100000];
	 s1=scan.next();
	 s2=scan.next();
	 s3=scan.next();
	 for(i=0;i<=s1.length()-s2.length()-s3.length();++i)
		{
		 if(s1.substring(i,i+s2.length()).equals(s2))
			for(j=i+s2.length();j<=s1.length()-s3.length();++j)
				if(s1.substring(j,j+s3.length()).equals(s3))
					{
					 ++flag;
					 break;
					}
		 if(flag==1)
			break;
		}
	 ch=s1.toCharArray();
	 for(i=0,j=s1.length()-1;i<s1.length();++i,--j)
		ch1[j]=ch[i];
	 s1=String.valueOf(ch1);
	 for(i=0;i<=s1.length()-s2.length()-s3.length();++i)
		{
		 if(s1.substring(i,i+s2.length()).equals(s2))
			for(j=i+s2.length();j<=s1.length()-s3.length();++j)
				if(s1.substring(j,j+s3.length()).equals(s3))
					{
					 flag+=2;
					 break;
					}
		 if(flag==3)
			break;
		}
	 if(flag==3)
		System.out.println("both");
	 else if(flag==2)
		System.out.println("backward");
	 else if(flag==1)
		System.out.println("forward");
	 else
		System.out.println("fantasy");
 	}
}

Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

/**
 * ******* Created on 23/10/19 7:01 PM*******
 */

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

public class A8 implements Runnable {

    private void solve() throws IOException {
        String platform = reader.next();
        String first = reader.next();
        String second = reader.next();
        int n =platform.length();
        String[] output={"fantasy","forward", "backward", "both"};
        int mask =0;
        for(int l=0;l<2;l++){
            boolean flag =false;
            int index = platform.indexOf(first);
            if(index !=-1)
                flag =  platform.indexOf(second, index+first.length())!=-1;
            platform = new StringBuilder(platform).reverse().toString();
            if(flag ==true){
                mask |= (1<<l);
            }
        }
        writer.println(output[mask]);

    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new A8().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    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': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

import java.util.*;

public class zer {

	static Scanner in = new Scanner(System.in);

	public static void main(String[] args) {

		int n = in.nextInt();
		int m = in.nextInt();
		int[] p = new int[n];
		List<Set<Integer>> tab = new ArrayList<>();
		for(int i = 0; i < n; i++) {
			p[i] = in.nextInt();
			tab.add(new HashSet<>());
		}
		int ans = 3000003;
		for(int i = 0; i < m; i++) {
			int a = in.nextInt()-1;
			int b = in.nextInt()-1;
			for(int x : tab.get(a)) {
				if(tab.get(b).contains(x))  {
					ans = Math.min(p[a] +  p[b] + p[x], ans);
				}
			}
			tab.get(a).add(b);
			tab.get(b).add(a);
		}
		if(ans == 3000003) System.out.println(-1);
		else System.out.println(ans);
	}
}


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {

        int n;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int ai[] = new  int[n];

        int count = 0 ;
        for (int i = 0; i < n; i++) {
            ai[i]=sc.nextInt();
        }

        int min = ai[0] ;
        int max= ai[0];
        int min_index = 0 , max_index = 0 ;

        for (int i = 0; i < n; i++) {
            if (ai[i] == min  ) {
                min_index = i;
            }
                if (ai[i] < min  ) {
                    min_index = i;
            }
                else if (ai[i] > max ) {
                max_index = i;
            }
        }
        System.out.println("min index = "+ min_index);
        System.out.println("max index = "+ max_index);
        if ( min_index < max_index) {
            System.out.println(max_index - 1 + n - min_index - 1);
        }
        else if ( min_index > max_index) {
            System.out.println(max_index + (n - min_index) );
        }

    }
}

A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int ai[] = new int[n];
        for (int i = 0; i < n; i++) {
            ai[i] = sc.nextInt();
        }
        int count = 0;
        int min = ai[0];
        int max = ai[0];
        int min_index = 0, max_index = 0;

        for (int i = 0; i < n; i++) {
            if (min >= ai[i] ) {
                min = ai[i];
                min_index = i;
            }

            if (max < ai[i]) {
                max = ai[i];
                max_index = i;

            }
        }
        if ( min_index < max_index) {
            System.out.println((max_index - 1) + ((n - 1) - min_index  )  );
        }
        else if ( min_index > max_index) {
                System.out.println(max_index + ((n - 1) - min_index) );
            }
        }

    }


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

public class Test03 {

	public  void run() throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine();
		String[] lines = line.split("\\s+");
		int n = Integer.parseInt(lines[0]);
		int m = Integer.parseInt(lines[1]);

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

		int ret = 0;
		for(int i = 1; i <= n; i++){
			if(!f[i]){
				ret++;
				if(i == n){
					break;
				}
				int yoko = 1;
				int tate = 1;
				int x = i;
				int y = 1;
				int motox = x;
				int motoy = y;
				while(true){
					x += yoko;
					y += tate;
					if(x == 1 && y == 1){
						yoko = 1;
						tate = 1;
					}
					else if(x == n && y == 1){
						yoko = -1;
						tate = 1;
					}
					else if(x == 1 && y == m){
						yoko = 1;
						tate = -1;
					}
					else if(x == n && y == m){
						yoko = -1;
						tate = -1;
					}
					else if(x == 1){
						yoko = 1;
					}
					else if(x == n){
						yoko = -1;
					}
					else if(y == 1){
						tate = 1;
					}
					else if(y == m){
						tate = -1;
					}
					if(y == 1){
						f[x] = true;
					}
					if(x == motox && y == motoy && yoko == 1 && tate == 1){
						break;
					}
				}
			}
		}

		System.out.println(ret);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		Test03 t = new Test03();
		t.run();
	}

}

Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.  It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

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 F {

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

		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt(), m = sc.nextInt();
		UnionFind uf = new UnionFind(m);
		int[] r = new int[m];
		Arrays.fill(r, -1);
		for(int c = 0; c < m; ++c)
		{
			int x = (c + n - 1)%(2 * m - 2);
			if(x >= m)
				x = 2 * m - x - 2;
			r[x] = uf.union(c, r[x]);
			int cc = m - 1 - c;
			int y = (cc + n - 1)%(2 * m - 2);
			if(y >= m)
				y = 2 * m - y - 2;
			y = m - 1 - y;
			r[y] = uf.union(m - 1 - cc, r[y]);
		}
		out.println(uf.sets);
		out.flush();
		out.close();
	}

	static class UnionFind
	{
		int[] rank, p;
		int sets;

		UnionFind(int N)
		{
			rank = new int[N];
			p = new int[N];
			for(int i = 0; i < N; ++i)
				p[i] = i;
			sets = N;
		}

		int find(int x) { return x == p[x] ? x : (p[x] = find(p[x])); }

		int union(int x, int y)
		{
			x = find(x);
			if(y == -1)
				return x;
			y = find(y);

			if(x == y)
				return x;
			if(rank[x] > rank[y])
				p[y] = x;
			else
			{
				p[x] = y;
				if(rank[x] == rank[y])
					++rank[y];
			}
			--sets;
			return p[x];
		}
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

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

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

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

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

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

	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

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

    static class TaskD {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int S = in.nextInt();
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();

            int sum = a + b + c;
            if (sum == 0) {
                out.printf("%.6f %.6f %.6f", 0, 0, 0);
                return;
            }

            double da = (double) a / (double) sum;
            double db = (double) b / (double) sum;
            double dc = (double) c / (double) sum;

            double ans1 = da * S;
            double ans2 = db * S;
            double ans3 = dc * S;

            out.printf("%.12f %.12f %.12f", ans1, ans2, ans3);
        }

    }
}

As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1.

The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists.

Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) =  - ∞.

import java.util.*;
import java.io.*;
public class Main {
    static class Scan {
        private byte[] buf=new byte[1024];
        private int index;
        private InputStream in;
        private int total;
        public Scan()
        {
            in=System.in;
        }
        public int scan()throws IOException
        {
            if(total<0)
            throw new InputMismatchException();
            if(index>=total)
            {
                index=0;
                total=in.read(buf);
                if(total<=0)
                return -1;
            }
            return buf[index++];
        }
        public int scanInt()throws IOException
        {
            int integer=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    integer*=10;
                    integer+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            return neg*integer;
        }
        public double scanDouble()throws IOException
        {
            double doub=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n)&&n!='.')
            {
                if(n>='0'&&n<='9')
                {
                    doub*=10;
                    doub+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            if(n=='.')
            {
                n=scan();
                double temp=1;
                while(!isWhiteSpace(n))
                {
                    if(n>='0'&&n<='9')
                    {
                        temp/=10;
                        doub+=(n-'0')*temp;
                        n=scan();
                    }
                    else throw new InputMismatchException();
                }
            }
            return doub*neg;
        }
        public String scanString()throws IOException
        {
            StringBuilder sb=new StringBuilder();
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            while(!isWhiteSpace(n))
            {
                sb.append((char)n);
                n=scan();
            }
            return sb.toString();
        }
        private boolean isWhiteSpace(int n)
        {
            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
            return true;
            return false;
        }
    }

    public static void sort(int arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(int arr[],int l1,int r1,int l2,int r2) {
        int tmp[]=new int[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void sort(long arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(long arr[],int l1,int r1,int l2,int r2) {
        long tmp[]=new long[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void main(String args[]) throws IOException {
        Scan input=new Scan();
        double s=input.scanInt();
        double a=input.scanInt();
        double b=input.scanInt();
        double c=input.scanInt();
        if(a==0 && b==0 && c==0) {
            System.out.println(0+" "+0+" "+0);
            return;
        }
        System.out.print((a*s)/(a+b+c));
        System.out.print(" ");
        System.out.print((b*s)/(a+b+c));
        System.out.print(" ");
        System.out.print((c*s)/(a+b+c));
        System.out.println();
    }
}


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

public class Solution {
    int solve(int n, int x, int[] a) {
        Arrays.sort(a);

        if (x == 2)
            return 0;

        if (a.length == 0)
            return -1;

        if (a[0] == 1)
            return 1;

        int MAX = 2000001;

        boolean[] isPrime = new boolean[MAX];
        Arrays.fill(isPrime, true);
        int primeCnt = 0;
        for (int i=2; i < x; i++) if (isPrime[i]) {
            if (Arrays.binarySearch(a, i) < 0)
                return -1;

            primeCnt++;
            for (int j = 2*i; j < MAX; j += i)
                isPrime[j] = false;
        }

        return primeCnt;
    }

    int bruteForce(int n, int x, int[] a) {
        int[][] sign = new int[x+1][n];
        for (int i=2; i<=x; i++)
            for (int j=0; j<n; j++)
                sign[i][j] = (i + a[j] - 1) / a[j];

        for (int i=2; i<x; i++)
            if (Arrays.equals(sign[i], sign[i+1]))
                return -1;

        int ans = n + 1;
        for (int mask=0; mask < (1<<n); mask++) {
            boolean ok = true;
            for (int i=2; i<x; i++) {
                boolean eq = true;
                for (int j=0; j < n; j++) if ((mask & (1<<j)) != 0 && sign[i][j] != sign[i+1][j]) {
                    eq = false;
                    break;
                }
                if (eq) {
                    ok = false;
                    break;
                }
            }
            if (ok) ans = Math.min(ans, Integer.bitCount(mask));
        }

        return ans;
    }

    public void go() throws Exception {
        int n = -1, x = -1;
        int[] a;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine().trim());
            n = Integer.parseInt(st.nextToken());
            if (n<0 || n>100000) while (true);
            x = Integer.parseInt(st.nextToken());
            if (x<2 || x>1000000000) while (true);
            st = new StringTokenizer(br.readLine().trim());
            a = new int[n];
            for (int i=0; i<n; i++) {
                a[i] = Integer.parseInt(st.nextToken());
                if (a[i]<1 || a[i]>1000000000) while (true);
            }
            br.close();
        }
        catch (Exception e) {
            while (true);
        }

        System.out.println(solve(n,x,a));
    }

    public static void main(String[] args) throws Exception {
        /*Random rnd = new Random();
        int it = 0;
        while (true) {
            it++;
            if (it%1000==0) System.out.println(it);
            int n = rnd.nextInt(11);
            int x = rnd.nextInt(100-2+1)+2;
            int max = rnd.nextInt(100) + 1;
            int[] a = new int[n];
            for (int i=0; i<n; i++) a[i] = rnd.nextInt(max) + 1;

            int ans1 = new Solution().solve(n,x,a.clone());
            int ans2 = new Solution().bruteForce(n,x,a.clone());

            if (ans1 != ans2) {
                System.out.println(n);
                System.out.println(x);
                for (int i=0; i < n; i++)
                    System.out.println(a[i]);

                System.out.println(ans1+" "+ans2);
                System.exit(0);
            }
        }*/
        (new Solution()).go();
    }
}

Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.

The first line contains two integers n and x (0 ≤ n ≤ 105, 2 ≤ x ≤ 109). The second line contains integers ai (1 ≤ ai ≤ 109). Some numbers among all ai may be equal.

Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output  - 1.

NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.

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

public class Solution {
    int solve(int n, int x, int[] a) {
        Arrays.sort(a);

        if (x == 2)
            return 0;

        if (a.length == 0)
            return -1;

        if (a[0] == 1)
            return 1;

        int MAX = 2000001;

        boolean[] isPrime = new boolean[MAX];
        Arrays.fill(isPrime, true);
        int primeCnt = 0;
        for (int i=2; i < x; i++) if (isPrime[i]) {
            if (Arrays.binarySearch(a, i) < 0)
                return -1;

            primeCnt++;
            for (int j = 2*i; j < MAX; j += i)
                isPrime[j] = false;
        }

        return primeCnt;
    }

    int bruteForce(int n, int x, int[] a) {
        int[][] sign = new int[x+1][n];
        for (int i=2; i<=x; i++)
            for (int j=0; j<n; j++)
                sign[i][j] = (i + a[j] - 1) / a[j];

        for (int i=2; i<x; i++)
            if (Arrays.equals(sign[i], sign[i+1]))
                return -1;

        int ans = n + 1;
        for (int mask=0; mask < (1<<n); mask++) {
            boolean ok = true;
            for (int i=2; i<x; i++) {
                boolean eq = true;
                for (int j=0; j < n; j++) if ((mask & (1<<j)) != 0 && sign[i][j] != sign[i+1][j]) {
                    eq = false;
                    break;
                }
                if (eq) {
                    ok = false;
                    break;
                }
            }
            if (ok) ans = Math.min(ans, Integer.bitCount(mask));
        }

        return ans;
    }

    public void go() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int x = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());
        int[] a = new int[n];
        for (int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
        br.close();

        System.out.println(solve(n,x,a.clone()));
    }

    public static void main(String[] args) throws Exception {
        /*Random rnd = new Random();
        int it = 0;
        while (true) {
            it++;
            if (it%1000==0) System.out.println(it);
            int n = rnd.nextInt(11);
            int x = rnd.nextInt(100-2+1)+2;
            int max = rnd.nextInt(100) + 1;
            int[] a = new int[n];
            for (int i=0; i<n; i++) a[i] = rnd.nextInt(max) + 1;

            int ans1 = new Solution().solve(n,x,a.clone());
            int ans2 = new Solution().bruteForce(n,x,a.clone());

            if (ans1 != ans2) {
                System.out.println(n);
                System.out.println(x);
                for (int i=0; i < n; i++)
                    System.out.println(a[i]);

                System.out.println(ans1+" "+ans2);
                System.exit(0);
            }
        }*/
        (new Solution()).go();
    }
}


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

public class P75D {

    static boolean multipleIndependent = false;

    void run() {
        int n = in.nextInt(), m = in.nextInt();
        int[][] arrays = new int[n][];
        for (int i = 0; i < n; i++) {
            arrays[i] = in.nextIntArray(in.nextInt());
        }
        int[] bigArray = in.nextIntArray(m);
        long[] sums = new long[n];
        long[] maxPrefixes = new long[n];
        long[] maxPostfixes = new long[n];
        long[] maxWithins = new long[n];
        for (int i = 0; i < n; i++) {
            sums[i] = sum(arrays[i]);
            maxPrefixes[i] = maxPrefix(arrays[i]);
            maxPostfixes[i] = maxPostfix(arrays[i]);
            maxWithins[i] = maxWithin(arrays[i]);
        }
        long max = Long.MIN_VALUE;
        long[][] dp = new long[m][2];
        dp[0][0] = maxWithins[bigArray[0] - 1];
        dp[0][1] = maxPostfixes[bigArray[0] - 1];
        for (int i = 1; i < m; i++) {
            int curArr = bigArray[i] - 1;
            dp[i][0] = Math.max(maxWithins[curArr], dp[i - 1][1] + maxPrefixes[curArr]);
            dp[i][1] = Math.max(maxPostfixes[curArr], dp[i - 1][1] + sums[curArr]);
        }
        for (long[] ls : dp) {
            max = Math.max(max, ls[0]);
            max = Math.max(max, ls[1]);
        }
        out.println(max);
    }

    long sum(int[] arr) {
        long sum = 0;
        for (int a : arr) {
            sum += a;
        }
        return sum;
    }

    long maxPostfix(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            sum = sum + arr[i];
            max = Math.max(max, sum);
        }
        return max;
    }

    long maxPrefix(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int a : arr) {
            sum = sum + a;
            max = Math.max(max, sum);
        }
        return max;
    }

    long maxWithin(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int a : arr) {
            sum = Math.max(sum + a, 0);
            max = Math.max(max, sum);
        }
        return max;
    }

    /* -----: Template :----- */
    static InputReader in;
    static PrintWriter out;

    public static void main(String[] args) {
        try (PrintWriter o = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))) {
            in = new InputReader(System.in);
            out = o;
            int q = multipleIndependent ? in.nextInt() : 1;
            while (q-- > 0) {
                new P75D().run();
            }
        }
    }

    static Integer[] toWrapper(int[] arr) {
        Integer[] res = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    static Integer[][] toWrapper(int[][] arr) {
        Integer[][] res = new Integer[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            res[i] = toWrapper(arr[i]);
        }
        return res;
    }

    static Long[] toWrapper(long[] arr) {
        Long[] res = new Long[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    static Long[][] toWrapper(long[][] arr) {
        Long[][] res = new Long[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            res[i] = toWrapper(arr[i]);
        }
        return res;
    }

    static class InputReader {

        private final BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            int bufferSize = 32 * 1024;
            reader = new BufferedReader(new InputStreamReader(stream), bufferSize);
            tokenizer = null;
        }

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

        public String nextLine() {
            if (true) {
                throw new RuntimeException("nextLine: not tested");
            }
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            StringBuilder sb = new StringBuilder();
            return tokenizer.nextToken("\n");
        }

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

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

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public int[][] nextIntMap(int n, int m) {
            int[][] map = new int[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = nextIntArray(m);
            }
            return map;
        }

        public long[][] nextLongMap(int n, int m) {
            long[][] map = new long[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = nextLongArray(m);
            }
            return map;
        }

        public char[][] nextCharMap(int n) {
            char[][] map = new char[n][];
            for (int i = 0; i < n; i++) {
                map[i] = next().toCharArray();
            }
            return map;
        }
    }
}

Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

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

public class P75D {

    static boolean multipleIndependent = false;

    void run() {
        int n = in.nextInt(), m = in.nextInt();
        int[][] arrays = new int[n][];
        for (int i = 0; i < n; i++) {
            arrays[i] = in.nextIntArray(in.nextInt());
        }
        int[] bigArray = in.nextIntArray(m);
        long[] sums = new long[n];
        long[] maxPrefixes = new long[n];
        long[] maxPostfixes = new long[n];
        long[] maxWithins = new long[n];
        for (int i = 0; i < n; i++) {
            sums[i] = sum(arrays[i]);
            maxPrefixes[i] = maxPrefix(arrays[i]);
            maxPostfixes[i] = maxPostfix(arrays[i]);
            maxWithins[i] = maxWithin(arrays[i]);
        }
        long max = Long.MIN_VALUE;
        long[][] dp = new long[m][2];
        dp[0][0] = maxWithins[bigArray[0] - 1];
        dp[0][1] = maxPostfixes[bigArray[0] - 1];
        for (int i = 1; i < m; i++) {
            int curArr = bigArray[i] - 1;
            dp[i][0] = Math.max(maxWithins[curArr], dp[i - 1][1] + maxPrefixes[curArr]);
            dp[i][1] = Math.max(maxPostfixes[curArr], dp[i - 1][1] + sums[curArr]);
        }
        for (long[] ls : dp) {
            max = Math.max(max, ls[0]);
            max = Math.max(max, ls[1]);
        }
        out.println(max);
    }

    long sum(int[] arr) {
        long sum = 0;
        for (int a : arr) {
            sum += a;
        }
        return sum;
    }

    long maxPostfix(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            sum = sum + arr[i];
            max = Math.max(max, sum);
        }
        return max;
    }

    long maxPrefix(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int a : arr) {
            sum = sum + a;
            max = Math.max(max, sum);
        }
        return max;
    }

    long maxWithin(int[] arr) {
        long max = Long.MIN_VALUE;
        long sum = 0;
        for (int a : arr) {
            sum = Math.max(sum + a, a);
            max = Math.max(max, sum);
        }
        return max;
    }

    /* -----: Template :----- */
    static InputReader in;
    static PrintWriter out;

    public static void main(String[] args) {
        try (PrintWriter o = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))) {
            in = new InputReader(System.in);
            out = o;
            int q = multipleIndependent ? in.nextInt() : 1;
            while (q-- > 0) {
                new P75D().run();
            }
        }
    }

    static Integer[] toWrapper(int[] arr) {
        Integer[] res = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    static Integer[][] toWrapper(int[][] arr) {
        Integer[][] res = new Integer[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            res[i] = toWrapper(arr[i]);
        }
        return res;
    }

    static Long[] toWrapper(long[] arr) {
        Long[] res = new Long[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    static Long[][] toWrapper(long[][] arr) {
        Long[][] res = new Long[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            res[i] = toWrapper(arr[i]);
        }
        return res;
    }

    static class InputReader {

        private final BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            int bufferSize = 32 * 1024;
            reader = new BufferedReader(new InputStreamReader(stream), bufferSize);
            tokenizer = null;
        }

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

        public String nextLine() {
            if (true) {
                throw new RuntimeException("nextLine: not tested");
            }
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            StringBuilder sb = new StringBuilder();
            return tokenizer.nextToken("\n");
        }

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

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

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public int[][] nextIntMap(int n, int m) {
            int[][] map = new int[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = nextIntArray(m);
            }
            return map;
        }

        public long[][] nextLongMap(int n, int m) {
            long[][] map = new long[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = nextLongArray(m);
            }
            return map;
        }

        public char[][] nextCharMap(int n) {
            char[][] map = new char[n][];
            for (int i = 0; i < n; i++) {
                map[i] = next().toCharArray();
            }
            return map;
        }
    }
}


import javax.swing.*;
import java.io.PrintWriter;
import java.util.Scanner;

public class SaveTheCity {
    public static int n;
    public static Vertices[] vertices;
    static class Vertices{
        int x,y;
        Vertices(int x, int y){
            this.x=x;
            this.y=y;
        }
    }

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

    public static void main(String[] args) {
        Scanner cin= new Scanner(System.in);
        PrintWriter pw= new PrintWriter(System.out);
        n=cin.nextInt();
        vertices= new Vertices[n];
        for(int i=0;i<n;i++){
            int x= cin.nextInt();
            int y= cin.nextInt();
            vertices[i]= new Vertices(x,y);
        }
        boolean change= vertices[0].x<vertices[1].x;
        int x=vertices[1].x, y=vertices[1].y;
        for(int i=0;i<n;i++){
            vertices[i].x-=x;
            vertices[i].y-=y;
            if(change){
                vertices[i].x=-vertices[i].x;
                vertices[i].y=-vertices[i].y;
            }
        }
        int l=0,r=vertices[0].x;
        for(int i=2;i+1<n;i++){
            long crossLeft=cross(i,i+1,0);
            long crossRight= cross(i,i+1,1);
            if(crossRight>0 && crossLeft>0){
                pw.println(0);
                return;
            }
            int x0 = vertices[i].x, y0 = vertices[i].y, x1 = vertices[i + 1].x, y1 = vertices[i + 1].y;
            if (crossRight > 0 || crossLeft > 0) {
                long p = (long) x0 * (y1 - y0) - (long) y0 * (x1 - x0);
                long q = y1 - y0;
                if (q < 0) {
                    p = -p; q = -q;
                }
                if (crossRight > 0)
                    r = Math.min(r, (int) (p / q));
                else
                    l = Math.max(l, (int) ((p + q - 1) / q));
            }
        }
        pw.println(l<=r?r-l+1:0);

    }

}

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

	}
}


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

public class Main {

  public static void main(String[] args) {

      Scanner sc = new Scanner(file);

      int N = sc.nextInt();
      boolean possible = true;
      boolean check = true;
      int[] numOfWord = new int[1001];
      int[] word = new int[N];

      for (int i = 0; i < N; i++) {
        int temp = sc.nextInt();
        numOfWord[temp]++;
        if (temp != 1 && numOfWord[temp] != 0)
          check = false;
        if ((temp != 1 && numOfWord[temp] > 1) || (!check && numOfWord[1] > 1)) {
          possible = false;
          break;
        }
        word[i] = temp;
      }

      if (!possible) {
        System.out.println("NO");
        return;
      }

      System.out.println("YES");

      for (int i = 0; i < N; i++) {
        for (int j = 0; j < word[i] - 1; j++)
          System.out.print(1);
        System.out.println(0);
      }

      sc.close();

  }

}

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

  }

}


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

public class CF229D {
	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[] h = new int[n];
		for (int i = 0; i < n; i++)
			h[i] = in.nextInt();
		int[] sum = new int[n];
		for (int i = 0; i < n; i++)
			sum[i] = (i == 0 ? 0 : sum[i - 1]) + h[i];
		int[][] dp = new int[n][n];
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				dp[i][j] = Integer.MAX_VALUE;
		for (int i = 0; i < n; i++)
			dp[i][0] = i;
		for (int used = 0; used < n; used++)
			for (int last = 0; last < n; last++)
				if (dp[used][last] != Integer.MAX_VALUE) {
					if (used < n - 1)
						dp[used + 1][last] = Math.min(dp[used + 1][last], dp[used][last] + 1);
					int curSum = sum[used] - (used > last ? sum[used - last - 1] : 0);
					if (sum[n - 1] - sum[used] < curSum)
						continue;
					int l = 0, r = n - 1 - used;
					while (r - l > 1) {
						int m = (l + r) / 2;
						if (sum[m] - sum[used] >= curSum) {
							r = m;
						} else {
							l = m;
						}
					}
					dp[used + r][used + 1] = Math.min(dp[used + r][used + 1], dp[used][last] + r - 1);
				}
		int ans = Integer.MAX_VALUE;
		for (int i = 0; i < n; i++)
			ans = Math.min(ans, dp[n - 1][i]);
		out.println(ans);
	}

	void run() {
		try {
			in = new FastScanner(new File("object.in"));
			out = new PrintWriter(new File("object.out"));

			solve();

			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	void runIO() {

		in = new FastScanner(System.in);
		out = new PrintWriter(System.out);

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

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

		boolean hasMoreTokens() {
			while (st == null || !st.hasMoreTokens()) {
				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (s == null)
					return false;
				st = new StringTokenizer(s);
			}
			return true;
		}

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

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

	public static void main(String[] args) {
		new CF229D().runIO();
	}
}

The city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from left to right.The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands i-th and put it on the top of either the (i - 1)-th tower (if it exists), or the (i + 1)-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1.Help the mayor determine the minimum number of operations required to make the city beautiful.

The first line contains a single integer n (1 ≤ n ≤ 5000) — the number of towers in the city. The next line contains n space-separated integers: the i-th number hi (1 ≤ hi ≤ 105) determines the height of the tower that is i-th (from left to right) in the initial tower sequence.

Print a single integer — the minimum number of operations needed to make the city beautiful.

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.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);
        DTowers solver = new DTowers();
        solver.solve(1, in, out);
        out.close();
    }

    static class DTowers {
        int MAXN = 5005;
        PrintWriter out;
        InputReader in;
        int n;
        long[] pf = new long[MAXN];
        long[][] dp = new long[MAXN][MAXN];

        long go(int ind, int last) {
            if (ind == n + 1)
                return 0;
            if (dp[ind][last] != -1)
                return dp[ind][last];
            long val = 1 + go(ind + 1, last);
            long last_sum = pf[ind - 1] - pf[last];
            int lo = ind, hi = n - 1;
            while (lo <= hi) {
                int mid = (lo + hi) >> 1;
                if (pf[mid] - pf[ind - 1] < last_sum)
                    lo = mid + 1;
                else
                    hi = mid - 1;
            }
            lo++;
            //System.out.println(ind +" "+lo+" "+last);
            long nxt_sum = pf[lo - 1] - pf[ind - 1];
            if (pf[n] - pf[lo - 1] >= nxt_sum) {
                int len = lo - ind;
                long cost = len - 1;
                val = Math.min(val, go(lo, ind - 1) + cost);
            } else {
                int len = n + 1 - ind;
                long cost = len - 1;
                val = Math.min(val, go(n + 1, ind - 1) + cost);
            }
            dp[ind][last] = val;
            return val;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            this.out = out;
            this.in = in;
            n = ni();
            int i = 0;
            for (i = 1; i <= n; i++)
                pf[i] = pf[i - 1] + nl();
            for (i = 0; i <= n; i++)
                Arrays.fill(dp[i], -1);
            long min = (int) 1e9;
            if (n == 1) {
                pn(0);
                return;
            }
            for (i = 1; i <= n; i++) {
                //pn(i);
                if (pf[n] - pf[i] >= pf[i]) {
                    int len = i;
                    long cost = len - 1;
                    min = Math.min(min, go(i + 1, 0) + cost);
                } else {
                    int len = n;
                    long cost = len - 1;
                    min = Math.min(min, go(n + 1, 0) + cost);
                }
            }
            pn(min);
        }

        int ni() {
            return in.nextInt();
        }

        long nl() {
            return in.nextLong();
        }

        void pn(long zx) {
            out.println(zx);
        }

    }

    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 long nextLong() {
            return Long.parseLong(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;
        }

    }
}


import java.util.*;

public class Test {

    static int[] a = new int[40_000_000];
    static int cnt;

    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        int n = sca.nextInt(), k = sca.nextInt();
        int[] ns = new int[n];

        for (int i = 0; i < n; i++) {
            ns[i] = sca.nextInt();
            segs(ns[i]);
        }

        Arrays.sort(a, 0, cnt);
//        System.out.println(Arrays.toString(Arrays.copyOf(a, cnt)));

        int prev = 2_000_000_000;
        for (int i = cnt - 1; i >= 0; i--) {
            if (a[i] == prev) continue;
            int d = a[i];

            // Compute sum;
            long s = 0, t = 0;
            for (int j = 0; j < ns.length; j++) {
                int r = (ns[j] + d - 1)/d;
                t += r;
                s += r*d - ns[j];
            }
//            System.out.println(d + " " + s + " " + t);

            if (s <= k) {
                if (d < prev - 1) {
                    long w = (k - s)/t;
                    d += w;
                }
                System.out.println(d);
                return;
            }
            prev = d;
        }
    }

    static void segs(int d) {
        for (int i = 1; i <= Math.sqrt(d); i++) {
            a[cnt++] = i;
            a[cnt++] = (d + i - 1)/i;
        }
    }
}

Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1011) — the number of bamboos and the maximum total length of cut parts, in meters. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the required heights of bamboos, in meters.

Print a single integer — the maximum value of d such that Vladimir can reach his goal.

NoteIn the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Test {

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

  public static void main(String[] args) {
    Test te = new Test();
    te.start();
    writer.flush();
  }

  int readInt() {
    int ans = 0;
    boolean neg = false;
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c == '-') {
          start = true;
          neg = true;
          continue;
        } else if (c >= '0' && c <= '9') {
          start = true;
          ans = ans * 10 + c - '0';
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return neg ? -ans : ans;
  }

  long readLong() {
    long ans = 0;
    boolean neg = false;
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c == '-') {
          start = true;
          neg = true;
          continue;
        } else if (c >= '0' && c <= '9') {
          start = true;
          ans = ans * 10 + c - '0';
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return neg ? -ans : ans;
  }

  String readLine() {
    StringBuilder b = new StringBuilder();
    try {
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c == '\n') {
          break;
        } else {
          b.append((char) (c));
        }
      }
    } catch (IOException e) {
    }
    return b.toString().trim();
  }

  void start() {
    int n = readInt();
    long k = readLong();
    int[] a = new int[n];
    for (int i = 0; i < n; k += a[i], i++) a[i] = readInt();
    long ans = Long.MIN_VALUE;
    for (long i = 1; i * i <= k; i++) {
      long c = k / i;
      for (int j = 0; j < n; j++) c -= (a[j] + i - 1) / i;
      if (c >= 0) ans = Math.max(ans, i);
      c = i;
      long d = k / i;
      for (int j = 0; j < n; j++) c -= (a[j] + d - 1) / d;
      if (c >= 0) ans = Math.max(ans, d);
    }
    writer.println(ans);
  }
}


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

public class ToAddorNottoAdd {

	// https://codeforces.com/contest/231/problem/C

	public static void main(String[] args) throws IOException, FileNotFoundException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		//BufferedReader in = new BufferedReader(new FileReader("ToAddorNottoAdd"));
		StringTokenizer st = new StringTokenizer(in.readLine());
		int n = Integer.parseInt(st.nextToken());
		long k = Integer.parseInt(st.nextToken());
		long[] arr = new long[n];
		st = new StringTokenizer(in.readLine());
		for (int i=0; i<n; i++) arr[i] = Long.parseLong(st.nextToken());
		if (n == 1) System.out.println(1 + " " + arr[0]);
		Arrays.sort(arr);

		// 2 pointers
		int maxnum = 1;
		long number=arr[0];
		int firstpointer=0;
		for (int secondpointer=1; secondpointer<n; secondpointer++) {
			k -= (secondpointer-firstpointer)*(arr[secondpointer]-arr[secondpointer-1]);
			while (k < 0) {
				k += (arr[secondpointer] - arr[firstpointer]);
				firstpointer++;
			}
			if (secondpointer-firstpointer+1 > maxnum) {
				number = arr[secondpointer];
				maxnum = secondpointer-firstpointer+1;
			}
		}
		System.out.println(maxnum + " " + number);
	}
}

/*
long min = arr[0];
long max = arr[arr.length-1];
long curmax=0;
long maxnum=0;
	// first find max amount of times it could work
HashMap<Long, Long> map =new HashMap<>();
while (min < max) {
	long middle = (min+max)/2;
	map.put(middle, works(middle, arr, k));
	if (map.get(middle) > curmax) {
		curmax = map.get(middle);
		maxnum = middle;
		min = middle;
	}
	else max = middle-1;
}

// now that have curmax
for (long i=maxnum; i>=arr[0]; i--) {
	if (works(i, arr, k) == curmax) {
		maxnum = i;
	}
	else break;
}

System.out.println(curmax + " " + maxnum );

}

public static long works(long middle, long[] arr, long k) {
ArrayList<Long> a = new ArrayList<>();
for (int i=0; i<arr.length; i++) {
	if (arr[i] <= middle) a.add(arr[i]);
	else break;
}
long count=0;
int pointer=a.size()-1;
while (k>0 && pointer>=0) {
	if (middle - a.get(pointer) <= k) {
		k -= (middle - a.get(pointer));
		count++;
	}
	pointer--;
}
return count;
}

*/

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