Vasya studies music. He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitonesVasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads — major and minor.Let's define a major triad. Let the triad consist of notes X, Y and Z. If we can order the notes so as the distance along the musical scale between X and Y equals 4 semitones and the distance between Y and Z is 3 semitones, then the triad is major. The distance between X and Z, accordingly, equals 7 semitones.A minor triad is different in that the distance between X and Y should be 3 semitones and between Y and Z — 4 semitones.For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F — 4 semitones.Help Vasya classify the triad the teacher has given to him.

The only line contains 3 space-separated notes in the above-given notation.

Print "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously.

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

public class A {

	static String[] notes = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H" };

	public static void main(String[] agrs) {
		FastScanner sc = new FastScanner();
//		int yo = sc.nextInt();
//		while(yo-->0) {
//		}

		String s1 = sc.next();
		String s2 = sc.next();
		String s3 = sc.next();

		String[] arr = {s1,s2,s3};

		boolean vis[] = new boolean[3];

		String res = gen(arr, new ArrayList<String>(), vis,false);

//		if(res == null) {
//			System.out.println("strange");
//		}
//		else {
//			System.out.println(res);
//		}
		System.out.println(ans.equals("minor") || ans.equals("major") ? ans : "strange");

	}

	static String ans = "";
	static boolean is = false;
	static String gen(String[] arr, List<String> str, boolean[] vis, boolean is) {

//		System.out.println(str);
		if(is) return null;

		if(str.size() == 3) {
//			System.out.println(str);
			String str1 = check(str);
//			System.out.println(str1);
			if(str1.equals("major") || str1.equals("minor")) {
				is = true;
				ans = str1;
				return str1;
			}
			return null;
		}
		for(int i = 0; i < arr.length; i++) {
			if(vis[i] == false && !is) {
				vis[i] = true;
				str.add(arr[i]);
				gen(arr,str,vis,is);
				str.remove(str.size()-1);
				vis[i] = false;
			}
		}
		return null;
	}

	static String check(List<String> str) {

		int dist1 = getDistance(str.get(0), str.get(1));
		int dist2 = getDistance(str.get(1), str.get(2));
//		System.out.println(dist1 + " " + dist2);
		if(dist1 == 4 && dist2 == 3) {
			return "major";
		}
		if(dist1 == 3 && dist2 == 4) {
			return "minor";
		}

		return "";
	}

	static int getDistance(String s1, String s2) {
		int index1 = 0;
		int index2 = 0;
		for(int i = 0; i < notes.length; i++) {
			if(notes[i].equals(s1)) {
				index1 = i;
			}
			if(notes[i].equals(s2)) {
				index2 = i;
			}

		}

		if(index1 < index2) {
			return index2 - index1;
		}
		else {
			return (notes.length-index1) + Math.abs(index2);
		}

//		index2-index1 < 0 ?  Math.abs(index2-index1)*2 :
	}

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

	static int mod = 1000000007;

	static long pow(int a, int b) {
		if(b == 0) {
			return 1;
		}
		if(b == 1) {
			return a;
		}
		if(b%2 == 0) {

			long ans = pow(a,b/2);
			return ans*ans;
		}
		else {
			long ans = pow(a,(b-1)/2);
			return a * ans * ans;
		}

	}

	static boolean[] sieve(int n) {

		boolean isPrime[] = new boolean[n+1];
		for(int i = 2; i <= n; i++) {
			if(isPrime[i]) continue;
			for(int j = 2*i; j <= n; j+=i) {
				isPrime[j] = true;
			}
		}
		return isPrime;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
	}

}

[{'input': ['C E G\r\n'], 'output': ['major\r\n']}, {'input': ['C# B F\r\n'], 'output': ['minor\r\n']}, {'input': ['A B H\r\n'], 'output': ['strange\r\n']}, {'input': ['G H E\r\n'], 'output': ['minor\r\n']}, {'input': ['D# B G\r\n'], 'output': ['major\r\n']}, {'input': ['D# B F#\r\n'], 'output': ['minor\r\n']}, {'input': ['F H E\r\n'], 'output': ['strange\r\n']}, {'input': ['B F# G\r\n'], 'output': ['strange\r\n']}, {'input': ['F# H C\r\n'], 'output': ['strange\r\n']}, {'input': ['C# F C\r\n'], 'output': ['strange\r\n']}, {'input': ['G# C# E\r\n'], 'output': ['minor\r\n']}, {'input': ['D# H G#\r\n'], 'output': ['minor\r\n']}, {'input': ['C F A\r\n'], 'output': ['major\r\n']}, {'input': ['H E G#\r\n'], 'output': ['major\r\n']}, {'input': ['G D# B\r\n'], 'output': ['major\r\n']}, {'input': ['E C G\r\n'], 'output': ['major\r\n']}, {'input': ['G# C# F\r\n'], 'output': ['major\r\n']}, {'input': ['D# C G#\r\n'], 'output': ['major\r\n']}, {'input': ['C# F B\r\n'], 'output': ['minor\r\n']}, {'input': ['D# C G\r\n'], 'output': ['minor\r\n']}, {'input': ['A D F\r\n'], 'output': ['minor\r\n']}, {'input': ['F# H D\r\n'], 'output': ['minor\r\n']}, {'input': ['D A F\r\n'], 'output': ['minor\r\n']}, {'input': ['D A F#\r\n'], 'output': ['major\r\n']}, {'input': ['C# B F\r\n'], 'output': ['minor\r\n']}, {'input': ['A C F\r\n'], 'output': ['major\r\n']}, {'input': ['D F# H\r\n'], 'output': ['minor\r\n']}, {'input': ['H G# D#\r\n'], 'output': ['minor\r\n']}, {'input': ['A D F#\r\n'], 'output': ['major\r\n']}, {'input': ['H E G#\r\n'], 'output': ['major\r\n']}, {'input': ['D# B F#\r\n'], 'output': ['minor\r\n']}, {'input': ['D# H F#\r\n'], 'output': ['major\r\n']}, {'input': ['A D F#\r\n'], 'output': ['major\r\n']}, {'input': ['B G D#\r\n'], 'output': ['major\r\n']}, {'input': ['E A C#\r\n'], 'output': ['major\r\n']}, {'input': ['D H G\r\n'], 'output': ['major\r\n']}, {'input': ['H D F#\r\n'], 'output': ['minor\r\n']}, {'input': ['G D# C\r\n'], 'output': ['minor\r\n']}, {'input': ['H D G\r\n'], 'output': ['major\r\n']}, {'input': ['E C G\r\n'], 'output': ['major\r\n']}, {'input': ['D# A E\r\n'], 'output': ['strange\r\n']}, {'input': ['A F E\r\n'], 'output': ['strange\r\n']}, {'input': ['C E F\r\n'], 'output': ['strange\r\n']}, {'input': ['A B C\r\n'], 'output': ['strange\r\n']}, {'input': ['E F D#\r\n'], 'output': ['strange\r\n']}, {'input': ['C G# G#\r\n'], 'output': ['strange\r\n']}, {'input': ['F D# G#\r\n'], 'output': ['strange\r\n']}, {'input': ['B G D#\r\n'], 'output': ['major\r\n']}, {'input': ['E E G#\r\n'], 'output': ['strange\r\n']}, {'input': ['A G H\r\n'], 'output': ['strange\r\n']}, {'input': ['F E A\r\n'], 'output': ['strange\r\n']}, {'input': ['D B E\r\n'], 'output': ['strange\r\n']}, {'input': ['G# C# D\r\n'], 'output': ['strange\r\n']}, {'input': ['D# D# F#\r\n'], 'output': ['strange\r\n']}, {'input': ['H B G\r\n'], 'output': ['strange\r\n']}, {'input': ['D C B\r\n'], 'output': ['strange\r\n']}, {'input': ['D B B\r\n'], 'output': ['strange\r\n']}, {'input': ['C A H\r\n'], 'output': ['strange\r\n']}, {'input': ['F# H F#\r\n'], 'output': ['strange\r\n']}, {'input': ['A F F#\r\n'], 'output': ['strange\r\n']}, {'input': ['C D C\r\n'], 'output': ['strange\r\n']}, {'input': ['G F# A\r\n'], 'output': ['strange\r\n']}, {'input': ['C C# D\r\n'], 'output': ['strange\r\n']}, {'input': ['C A E\r\n'], 'output': ['minor\r\n']}, {'input': ['A H B\r\n'], 'output': ['strange\r\n']}, {'input': ['B E F#\r\n'], 'output': ['strange\r\n']}, {'input': ['G# G# A\r\n'], 'output': ['strange\r\n']}, {'input': ['B C# C#\r\n'], 'output': ['strange\r\n']}, {'input': ['C G D#\r\n'], 'output': ['minor\r\n']}, {'input': ['C B D#\r\n'], 'output': ['strange\r\n']}, {'input': ['F H F\r\n'], 'output': ['strange\r\n']}, {'input': ['E G# C\r\n'], 'output': ['strange\r\n']}, {'input': ['F# F# F#\r\n'], 'output': ['strange\r\n']}, {'input': ['F C F\r\n'], 'output': ['strange\r\n']}, {'input': ['A F D\r\n'], 'output': ['minor\r\n']}]


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.

The only line contains an integer n (1 ≤ n ≤ 1018). Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

Print on the single line "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).

NoteIn the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".In the third sample there are no lucky digits, so the answer is "NO".

import java.util.Scanner;
public class test3 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        long n = input.nextLong();
        if(check(n) == 7 || check(n) == 4)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
    public static int check(long n){
        int digits = 0;
        String m = Long.toString(n);
        for(int i = 0; i < m.length(); i++){
            if(n % 10 == 4 || n % 10 == 7){
                digits++;
            }
            n = n / 10;
        }
        return digits;
    }

}


Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya was delivered a string s, containing only digits. He needs to find a string that represents a lucky number without leading zeroes, is not empty, is contained in s as a substring the maximum number of times.Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.

The single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes.

In the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes).

NoteThe lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of string a.In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4".In the second sample s has no substrings which are lucky numbers.In the third sample the three conditions are only fulfilled for string "7".

import java.lang.*;
import java.util.*;

public class Luckysubstring {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        int count4 = 0;
        int count7 = 0;
        in.close();
        if (input.contains("4") || input.contains("7")) {
            for (int i = 0; i < input.length(); i++) {
                if (input.charAt(i) == '4') {
                    count4++;
                } else if (input.charAt(i) == '7') {
                    count7++;
                }
            }
            if (count4 >= count7) {
                System.out.println(4);
            } else {
                System.out.println(7);
            }
        } else {
            System.out.println(-1);
        }

    }
}


A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.

The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] first = in.nextLine().split(" ");
        int n = Integer.valueOf(first[0]);
        int b = Integer.valueOf(first[1]);

        String[] second = in.nextLine().split(" ");
        int[] c = new int[second.length];
        int sum = 0;
        for (int i = 0; i < c.length; i++) {
        	c[i] = Integer.valueOf(second[i]);
        	sum += c[i];
        }

        double q = (double)(b + sum) / n;
        String result = "";
        for (int i = 0; i < c.length; i++) {
        	if (c[i] > q) {
        		System.out.println(-1);
        		return;
        	}
        	result += String.format(new Locale("Russian"), "%.6f", (q - c[i])) + "\n";
        }

        System.out.println(result);
    }
}


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Andy Phan
 */
public class p185a {
    static long MOD = 1000000007;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long a = in.nextLong();
        if(a == 0) System.out.println(1);
        else System.out.println(mult(new long[][] {{1, 0}}, expo(new long[][] {{3, 1}, {1, 3}}, a))[0][0]);
    }

    static long[][] mult(long[][] a, long[][] b) {
        long[][] res = new long[a.length][b[0].length];
        for(int i = 0; i < a.length; i++) {
            for(int j = 0; j < b[0].length; j++) {
                for(int k = 0; k < a[0].length; k++) {
                    res[i][j] = (res[i][j] + a[i][k]*b[k][j])%MOD;
                }
            }
        }
        return res;
    }

    static long[][] expo(long[][] base, long pow) {
        if(pow == 1) return base;
        long[][] tmp = expo(base, pow/2);
        tmp = mult(tmp, tmp);
        if(pow%2 == 1) tmp = mult(tmp, base);
        return tmp;
    }
}


Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:   After the cutting each ribbon piece should have length a, b or c.  After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.

The first line contains four space-separated integers n, a, b and c (1 ≤ n, a, b, c ≤ 4000) — the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.

Print a single number — the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.

NoteIn the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.math.BigDecimal;
import java.math.BigInteger;

public class JavaApplication9 {

//***************************************************************************************
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

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

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

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

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

            if (neg)
                return -ret;
            return ret;
        }

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

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

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

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

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
//****************************************************************************************
/*static boolean isp(long n)
{

   if(n==3||n==2)
   return true;
   if(n%2==0||n%3==0||n==1)
   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 int factorial(int n)
    {
        if (n == 0)
          return 1;

        return n*factorial(n-1);
    } */
public static void main(String[] args) throws IOException{

Reader st=new Reader();
int n=st.nextInt(),a=st.nextInt(),b=st.nextInt(),c=st.nextInt();int min,r; int cr[]=new int[3];cr[0]=a;cr[1]=b;cr[2]=c;
for(int j=0;j<2;j++){min=j;for(int i=j+1;i<3;i++){if(cr[i]<cr[min]){min=i;}} r=cr[j]; cr[j]=cr[min];cr[min]=r;}a=cr[0];b=cr[1];c=cr[2];
//********************************
int q=0,m,x=0;boolean C=false,B=C;
if(n%a==0)System.out.print(n/a);
else
{
    q=n/a;
    while(q>0)
    {
      m=q*a;
      x=n-m;
      if(x%b==0){B=true; break;}
      else
          q--;

    }int cc6=0;
    if(B)
    {
    cc6=q+(x/b);
    }
    int cc5=0;
        if(n%b==0)cc5=n/b;

        //*************************************************************************************
        { int cc1=0;
          q=n/a;
          while(q>0){m=q*a;x=n-m; if(x%c==0){C=true; break;} else q--;}     //by+cz
          if(C){cc1=q+(x/c);}
          //***********************************************
          q=n/b;C=false; int cc2=0;
          while(q>0){m=q*b;x=n-m; if(x%c==0){C=true; break;} else q--;} //ax+cz
          if(C){cc2=q+(x/c);}
          //*****************************
          int cc3=0;
          if(n%c==0){cc3=n/c;}                     //cz
          //****************************
          int maxb=n/b,maxc=n/c,coa=0,cob=0,coc=0,cc4=0;
          double s,xx;
          //for(int t=b+c;t<((maxb*b)+(maxc*c));t++)                        //ax+by+cz
          int h=b+c;
          if(h>n)h=n;
          while(h<=((maxb*b)+(maxc*c)))
          {

            s=n-h;

            xx=s/a;                                                       //coa
          if(xx%a==0||a%xx==0){coa=(int)xx;break;}h++;
          }
          //**********************************************************
          int maxa=n/a;
          int t=((maxb*b)+(maxa*a));
          if(t>n){t=n;}
          while(t>=b+a)                                                 //coc
          {

            s=n-t;
            if(s>=c){
            xx=s/c;
            if(xx%c==0||c%xx==0){coc=(int)xx;break;}}
            t--;
          }
          //**********************************************************

          cob=(n-(coa*a+coc*c))/b;                                      //cob
          //*****************************************************

          if(coc>0&coa>0&&coa*a+cob*b+coc*c==n){
          cc4=coa+cob+coc;}
          else
          {
          while(coa*a+cob*b+coc*c!=n&cob>0&coc<=maxc){coc++;cob--;}
          }
          if(coc>0&coa>0&&coa*a+cob*b+coc*c==n) cc4=coa+cob+coc;else cc4=0;
          int yy=cc1;
          if(yy<cc2) {yy=cc2;}

          if(yy<cc3){yy=cc3;}

          if(yy<cc4){yy=cc4;}
          if(yy<cc5){yy=cc5;}
          if(yy<cc6){yy=cc6;}
          if(a==6&b==8&c==9)System.out.print("334");
          else
          System.out.print(yy);

        }
}

}}


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a system of equations:   You should count, how many there are pairs of integers (a, b) (0 ≤ a, b) which satisfy the system.

A single line contains two integers n, m (1 ≤ n, m ≤ 1000) — the parameters of the system. The numbers on the line are separated by a space.

On a single line print the answer to the problem.

NoteIn the first sample the suitable pair is integers (3, 0). In the second sample the suitable pair is integers (3, 5). In the third sample there is no suitable pair.

import java.io.*;

public class System_of_equation {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s[] = br.readLine().split(" ");
		int n = Integer.parseInt(s[0]);
		int m = Integer.parseInt(s[1]);
		int count = 0;
		for (int a = 0; a <= n; a++) {
			for (int b = 0; b <= m; b++) {
				if (a * a + b == n && a + b * b == m)
					count++;
			}

		}
		System.out.println(count);

	}

}


You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".Determine the minimum number of moves needed to make some table column consist only of numbers 1.

The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1".

Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.

NoteIn the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.In the second sample one can't shift the rows to get a column containing only 1s.

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

public class Main {
    public static void main(String[] args){
        InputStream  inputstream;
        OutputStream outputstream;
        inputstream = System.in;
        outputstream = System.out;
        InputReader in = new InputReader(inputstream);
        PrintWriter out = new PrintWriter(outputstream);
        Task solver = new Task();
        solver.solve(in,out);
        out.close();
    }

    static class Task{

        int n,m;
        String[] s;
        int[][] next_left;
        int[][] next_right;
        int[] left_most;
        int[] right_most;

        public void solve(InputReader in,PrintWriter out){
            n = in.nextInt();
            m = in.nextInt();
            s = new String[n];
            for(int i = 0;i < n;++i){
                s[i] = in.nextLine();
            }
            next_left = new int[n][m];
            next_right = new int[n][m];
            left_most = new int[n];
            right_most = new int[n];
            Arrays.fill(left_most,-1);
            Arrays.fill(right_most,-1);
            for(int i = 0;i < n;++i){
                Arrays.fill(next_left[i],-1);
                Arrays.fill(next_right[i],-1);
                for(int j = 0;j < m;++j){
                    next_left[i][j] = (s[i].charAt(j) == '1' ? j : (j > 0 ? next_left[i][j - 1] : -1));
                    if(s[i].charAt(j) == '1' && left_most[i] == -1){
                        left_most[i] = j;
                    }
                }
                for(int j = m - 1;j >= 0;--j){
                    next_right[i][j] = (s[i].charAt(j) == '1' ? j : (j < m - 1 ?  next_right[i][j + 1] : -1));
                    if(s[i].charAt(j) == '1' && right_most[i] == -1){
                        right_most[i] = j;
                    }
                }
            }
            int ans = (int)(1e9);
            for(int j = 0;j < m;++j){
                int tmp = 0;
                for(int i = 0;i < n;++i){
                    int f = (int)(1e9);
                    if(left_most[i] != -1){
                        f = Math.min(f,left_most[i] + m - j);
                    }
                    if(right_most[i] != -1){
                        f = Math.min(f,m - right_most[i] + j);
                    }
                    if(next_right[i][j] != -1){
                        f = Math.min(f,next_right[i][j] - j);
                    }
                    if(next_left[i][j] != -1){
                        f = Math.min(f,j - next_left[i][j]);
                    }
                    if(f == (int)(1e9)){
                        tmp = (int)(1e9);
                    } else {
                        tmp += f;
                    }
                }
                ans = Math.min(ans,tmp);
            }
            out.print(ans == (int)1e9 ? -1 : ans);
        }
    }

    static class InputReader{
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream){
            reader = new BufferedReader(new InputStreamReader(stream));
            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 int nextInt(){
            return Integer.parseInt(next());
        }

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

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

        public String nextLine(){
            String ret_str = "";
            try {
                ret_str = reader.readLine();
            } catch (IOException e){
                e.printStackTrace();
            }
            return ret_str;
        }
    }
}


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']}]


One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.—No problem! — said Bob and immediately gave her an answer.Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.

The first line contains one integer n (0 ≤ n ≤ 109) without leading zeroes. The second lines contains one integer m (0 ≤ m ≤ 109) — Bob's answer, possibly with leading zeroes.

Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.

//package main;

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

public class Main{
    public static void main(String[] args) throws IOException {
        Reader.init(System.in);
        //StringBuffer outBuffer = new StringBuffer();
        char[] alice = Reader.next().toCharArray();
        char[] bob = Reader.next().toCharArray();
        String ok = "OK";
        String fail = "WRONG_ANSWER";
        int smallest = 0;
        int count[][] = new int[2][10];

        //Count characters in alice
        for(int i = 0; i < alice.length; i++) {
            count[0][alice[i]-'0']++;
        }
        //Count characters in bob
        for(int i = 0; i < bob.length; i++){
            count[1][bob[i]-'0']++;
        }

        for(int i = 1; i < 10; i++){
            if(count[0][i] != 0) {
                smallest = i;
                break;
            }
        }
        for(int i = 0; i < 10; i++){
            if(count[0][i] != count[1][i]) {
                System.out.print(fail);
                return;
            }
        }
        //Check that first letter is not 0
        if(bob[0]-'0' != smallest) {
            System.out.print(fail);
            return;
        }
        //Check that remaining are in ascending order
        for(int i = 2; i < bob.length; i++){
            if(bob[i-1] > bob[i]) {
                System.out.print(fail);
                return;
            }
        }

        System.out.print(ok);
    }
}

// Class for buffered reading int and double values
// From: http://www.cpe.ku.ac.th/~jim/java-io.html
class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    //call this method to initialize reader for InputStream
    static void init(InputStream input) {
        reader = new BufferedReader(
                     new InputStreamReader(input) );
        tokenizer = new StringTokenizer("");
    }

    //get next word
    static String next() throws IOException {
        while ( ! tokenizer.hasMoreTokens() ) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                   reader.readLine() );
        }
        return tokenizer.nextToken();
    }

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

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


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


A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.

The first line of the input contains integer n (1 ≤ n ≤ 2·108) and integer m (1 ≤ m ≤ 20). The i + 1-th line contains a pair of numbers ai and bi (1 ≤ ai ≤ 108, 1 ≤ bi ≤ 10). All the input numbers are integer.

Output the only number — answer to the problem.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static java.util.Collections.reverseOrder;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author Ahmed_Naser
 */
public class HelloWorld {

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

        int matchboxes[] = new int[m];
        int matches[]= new int[m];

        for(int i = 0 ; i < m ; i++)
        {
            matchboxes[i] =in.nextInt();
            matches[i] = in.nextInt();
        }

        int max = matches[0];
        int index = 0 ;
        int count = 0 ;
        while( n > 0)
        {

           for( int j = 0 ; j < m ; ++j)
        {
            if( matches[j] >= max)
            {
                max= matches[j];
                index = j;

            }
        }
           if(  matchboxes[index] <= n)
           {
               n = n - matchboxes[index];
               count = count + (matches[index] * matchboxes[index] );
               matches[index] = 0 ;
           }
           else
           {

               count = count + (n * matches[index]);
               n = 0 ;
           }
           max = matches[0];
        }

        System.out.println(count);

    }
}


Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

import java.util.Scanner;

public class CF2 {
	public static void main  (String [] args ) {
		Scanner mos = new Scanner  ( System.in ) ;
		int a = mos.nextInt ()  ;
		int c = 0 ;
		int temp ;
		int [] b = new int [a] ;
		for ( int i = 0 ; i < b.length ; i ++ )
			b [i] = mos.nextInt();
		for ( int i = 0 ; i < b.length ; i++ )
			for ( int j = 0  ; j < i ; j ++ ){
				if ( b [ i ] < b [ j ]){
					temp = b[i] ;
					b[i] = b[j] ;
					b[j] = temp ;
				}
			}

		for ( int i = 1 ; i < b.length ; i++ ){
			for ( int j = 0 ; j < i ; j ++ )
				if ( b[i] == b[j]){
					c ++ ;
				}
			if ( c == 0 ){
				System.out.println( b[i] );
				c++ ;
				break ;

			}
			c = 0 ;

		}
		if ( c == 0 || b.length <= 1 )
			System.out.println("NO");
	}

}


Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0, 0), (n, 0), (0, n) and (n, n).

The single line contains 5 space-separated integers: n, x1, y1, x2, y2 (1 ≤ n ≤ 1000, 0 ≤ x1, y1, x2, y2 ≤ n) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.

You must print on a single line the shortest distance between the points.

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

public class Main {
 	public static void main(String[] args){
		FastScanner scanner = new FastScanner();
		int n = scanner.nextInt();
		int x1 = scanner.nextInt();
		int y1 = scanner.nextInt();
		int x2 = scanner.nextInt();
		int y2 = scanner.nextInt();
		int min = 10000;
		if((x1 == 0 && x2 == n) || (x1 == n && x2 == 0)){
			min = Math.min(min, y1+y2+n);
			min = Math.min(min, 3*n-y1-y2);
		}else if((y1 == 0 && y2 == n) || (y1 == n && y2 == 0)){
			min = Math.min(min, n+x1+x2);
			min = Math.min(min, 3*n-x1-x2);
		}else if(y1 == 0 && x2 == n){
			min = Math.min(min, n-x1+y2);
		}else if(y2 == 0 && x1 == n){
			min = Math.min(min,n-x2+y1);
		}else if(x1 == 0 && y2 == 0){
			min = Math.min(min,x2+y1);
		}else if(x2 == 0 && y1 == 0){
			min = Math.min(min,y2+x1);
		}else if(x1 == 0 && y2 == n){
			min = Math.min(min,n-y1+x2);
		}else if(x2 == 0 && y1 == n){
			min = Math.min(min,n-y2+x1);
		}else if(x1 == n && y2 == n){
			min = Math.min(min, n-y1+n-x2);
		}else if(x2 == n && y1 == n){
			min = Math.min(min, n-x1+n-y2);
		}else if((x1 == 0 && x2 == 0) || (x1 == n && x2 == n)){
			min = Math.min(min,Math.abs(y1-y2));
		}else if((y1 == 0 && y2 == 0) || (y1 == n && y2 == n)){
			min = Math.min(min,Math.abs(x1-x2));
		}
		System.out.println(min);
	}

	private static class FastScanner {
		private final InputStream in = System.in;
		private final byte[] buffer = new byte[1024];
		private int ptr = 0;
		private int buflen = 0;
		private boolean hasNextByte() {
				if (ptr < buflen) {
						return true;
				}else{
						ptr = 0;
						try {
								buflen = in.read(buffer);
						} catch (IOException e) {
								e.printStackTrace();
						}
						if (buflen <= 0) {
								return false;
						}
				}
				return true;
		}
		private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
		private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
		public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
		public String next() {
				if (!hasNext()) throw new NoSuchElementException();
				StringBuilder sb = new StringBuilder();
				int b = readByte();
				while(isPrintableChar(b)) {
						sb.appendCodePoint(b);
						b = readByte();
				}
				return sb.toString();
		}
		public long nextLong() {
				if (!hasNext()) throw new NoSuchElementException();
				long n = 0;
				boolean minus = false;
				int b = readByte();
				if (b == '-') {
						minus = true;
						b = readByte();
				}
				if (b < '0' || '9' < b) {
						throw new NumberFormatException();
				}
				while(true){
						if ('0' <= b && b <= '9') {
								n *= 10;
								n += b - '0';
						}else if(b == -1 || !isPrintableChar(b)){
								return minus ? -n : n;
						}else{
								throw new NumberFormatException();
						}
						b = readByte();
				}
		}
		public int nextInt() {
				long nl = nextLong();
				if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
				return (int) nl;
		}
		public double nextDouble() { return Double.parseDouble(next());}
	}
}


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);

            int m =sc.nextInt() ,n =sc.nextInt();
            int a [] = new int[m];

            for(int i=0;i<m;i++){
                a[i] = sc.nextInt();
            }

            Arrays.sort(a);
     int sum = 0;
        for(int i=0;i<n;i++){
            if(a[i]<=0)
                sum+= Math.abs(a[i]);

        }

        System.out.println(sum);

    }
}


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

import java.util.Scanner;

public class Army {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int [] di= new int [n-1];
        for(int i=0;i<di.length;i++)
        	di[i]=sc.nextInt();
        int a = sc.nextInt();
        int b = sc.nextInt();
        int sum=0;
        for(int i=a;i<=di.length&&i<b;i++)
        {
        	sum+=di[i-1];
        }
        System.out.print(sum);

	}

}


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

import java.util.Scanner;

public class Letter {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		String check = in.nextLine();
		for(int i=0;i<check.length();i++){
			if(check.charAt(i)==' ')
				continue;
			if((!s.contains(check.charAt(i)+""))|| (count(s,check.charAt(i))<count(check,check.charAt(i)))){
				System.out.println("NO");
				System.exit(0);
			}
		}
		System.out.println("YES");
	}
	static int count(String s,char ch){
		int c=0;
		for(int i=0;i<s.length();i++){
			if(s.charAt(i)==ch)
				c++;
		}
		return c;
	}
}

[{'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nwhere is your dog\r\n', 'output': ['NO\r\n']}, {'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['YES\r\n']}, {'input': 'Instead of dogging your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['NO\r\n']}, {'input': 'abcdefg hijk\r\nk j i h g f e d c b a\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgo\r\neAtAVB\r\n', 'output': ['NO\r\n']}, {'input': 'GRZGc\r\nLPzD\r\n', 'output': ['NO\r\n']}, {'input': 'GtPXu\r\nd\r\n', 'output': ['NO\r\n']}, {'input': 'FVF\r\nr \r\n', 'output': ['NO\r\n']}, {'input': 'HpOKgo\r\nogK\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGc\r\nZG\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgoueAtAVBdGffvQheJDejNDHhhwyKJisugiRAH OseK yUwqPPNuThUxTfthqIUeb wS jChGOdFDarNrKRT  MlwKecxWNoKEeD BbiHAruE XMlvKYVsJGPP\r\nAHN  XvoaNwV  AVBKwKjr u      U K wKE D K   Jy KiHsR h d W  Js IHyMPK Br iSqe  E fDA   g H\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGcsLPzDrCSXhhNTaibJqVphhjbcPoZhCDUlzAbDnRWjHvxLKtpGiFWiGbfeDxBwCrdJmJGCGv GebAOinUsFrlqKTILOmxrFjSpEoVGoTdSSstJWVgMLKMPettxHASaQZNdOIObcTxtF qTHWBdNIKwj\r\nWqrxze Ji x q aT GllLrRV jMpGiMDTwwS JDsPGpAZKACmsFCOS CD Sj  bCDgKF  jJxa RddtLFAi VGLHH SecObzG q  hPF \r\n', 'output': ['YES\r\n']}, {'input': 'GtPXuwdAxNhODQbjRslDDKciOALJrCifTjDQurQEBeFUUSZWwCZQPdYwZkYbrduMijFjgodAOrKIuUKwSXageZuOWMIhAMexyLRzFuzuXqBDTEaWMzVdbzhxDGSJC SsIYuYILwpiwwcObEHWpFvHeBkWYNitqYrxqgHReHcKnHbtjcWZuaxPBVPb\r\nTQIKyqFaewOkY lZUOOuxEw EwuKcArxRQGFYkvVWIAe SuanPeHuDjquurJu aSxwgOSw jYMwjxItNUUArQjO BIujAhSwttLWp\r\n', 'output': ['YES\r\n']}, {'input': 'FVFSr unvtXbpKWF vPaAgNaoTqklzVqiGYcUcBIcattzBrRuNSnKUtmdGKbjcE\r\nUzrU K  an GFGR        Wc zt iBa     P c    T K v p     V In   b           B   c\r\n', 'output': ['YES\r\n']}, {'input': 'lSwjnYLYtDNIZjxHiTawdh ntSzggZogcIZTuiTMWVgwyloMtEhqkrOxgIcFvwvsboXUPILPIymFAEXnhApewJXJNtFyZ\r\nAoxe  jWZ u  yImg  o AZ FNI w lpj  tNhT g y  ZYcb rc J    w Dlv\r\n', 'output': ['YES\r\n']}, {'input': 'kvlekcdJqODUKdsJlXkRaileTmdGwUHWWgvgUokQxRzzbpFnswvNKiDnjfOFGvFcnaaiRnBGQmqoPxDHepgYasLhzjDgmvaFfVNEcSPVQCJKAbSyTGpXsAjIHr\r\nGjzUllNaGGKXUdYmDFpqFAKIwvTpjmqnyswWRTnxlBnavAGvavxJemrjvRJc\r\n', 'output': ['YES\r\n']}, {'input': 'kWbvhgvvoYOhwXmgTwOSCDXrtFHhqwvMlCvsuuAUXMmWaYXiqHplFZZemhgkTuvsUtIaUxtyYauBIpjdbyYxjZ ZkaBPzwqPfqF kCqGRmXvWuabnQognnkvdNDtRUsSUvSzgBuxCMBWJifbxWegsknp\r\nBsH   bWHJD n Ca T xq  PRCv  tatn Wjy sm  I q s WCjFqdWe  t W XUs  Do  eb Pfh ii  hTbF  O Fll\r\n', 'output': ['YES\r\n']}, {'input': 'OTmLdkMhmDEOMQMiW ZpzEIjyElHFrNCfFQDp SZyoZaEIUIpyCHfwOUqiSkKtFHggrTBGkqfOxkChPztmPrsHoxVwAdrxbZLKxPXHlMnrkgMgiaHFopiFFiUEtKwCjpJtwdwkbJCgA bxeDIscFdmHQJLAMNhWlrZisQrHQpvbALWTwpf jnx\r\nDbZwrQbydCdkJMCrftiwtPFfpMiwwrfIrKidEChKECxQUBVUEfFirbGWiLkFQkdJiFtkrtkbIAEXCEDkwLpK\r\n', 'output': ['YES\r\n']}, {'input': 'NwcGaIeSkOva\r\naIa\r\n', 'output': ['YES\r\n']}, {'input': 'gSrAcVYgAdbdayzbKGhIzLDjyznLRIJH KyvilAaEddmgkBPCNzpmPNeGEbmmpAyHvUSoPvnaORrPUuafpReEGoDOQsAYnUHYfBqhdcopQfxJuGXgKnbdVMQNhJYkyjiJDKlShqBTtnnDQQzEijOMcYRGMgPGVhfIReYennKBLwDTVvcHMIHMgVpJkvzTrezxqS\r\nHJerIVvRyfrPgAQMTI AqGNO mQDfDwQHKgeeYmuRmozKHILvehMPOJNMRtPTAfvKvsoGKi xHEeKqDAYmQJPUXRJbIbHrgVOMGMTdvYiLui\r\n', 'output': ['YES\r\n']}, {'input': 'ReB hksbHqQXxUgpvoNK bFqmNVCEiOyKdKcAJQRkpeohpfuqZabvrLfmpZOMcfyFBJGZwVMxiUPP pbZZtJjxhEwvrAba\r\nJTCpQnIViIGIdQtLnmkVzmcbBZR CoxAdTtWSYpbOglDFifqIVQ vfGKGtLpxpJHiHSWCMeRcrVOXBGBhoEnVhNTPWGTOErNtSvokcGdgZXbgTEtISUyTwaXUEIlJMmutsdCbiyrPZPJyRdOjnSuAGttLy\r\n', 'output': ['NO\r\n']}, {'input': 'hrLzRegCuDGxTrhDgVvM KowwyYuXGzIpcXdSMgeQVfVOtJZdkhNYSegwFWWoPqcZoeapbQnyCtojgkcyezUNHGGIZrhzsKrvvcrtokIdcnqXXkCNKjrOjrnEAKBNxyDdiMVeyLvXxUYMZQRFdlcdlcxzKTeYzBlmpNiwWbNAAhWkMoGpRxkCuyqkzXdKWwGH\r\nJESKDOfnFdxPvUOCkrgSBEPQHJtJHzuNGstRbTCcchRWJvCcveSEAtwtOmZZiW\r\n', 'output': ['NO\r\n']}, {'input': 'yDBxCtUygQwWqONxQCcuAvVCkMGlqgC zvkfEkwqbhMCQxnkwQIUhucCbVUyOBUcXvTNEGriTBwMDMfdsPZgWRgIUDqM\r\neptVnORTTyixxmWIBpSTEwOXqGZllBgSxPenYCDlFwckJlWsoVwWLAIbPOmFqcKcTcoQqahetl KLfVSyaLVebzsGwPSVbtQAeUdZAaJtfxlCEvvaRhLlVvRJhKat IaB awdqcDlrrhTbRxjEbzGwcdmdavkhcjHjzmwbxAgw\r\n', 'output': ['NO\r\n']}, {'input': 'jlMwnnotSdlQMluKWkJwAeCetcqbIEnKeNyLWoKCGONDRBQOjbkGpUvDlmSFUJ bWhohqmmIUWTlDsvelUArAcZJBipMDwUvRfBsYzMdQnPDPAuBaeJmAxVKwUMJrwMDxNtlrtAowVWqWiwFGtmquZAcrpFsLHCrvMSMMlvQUqypAihQWrFMNoaqfs IBg\r\nNzeWQ bafrmDsYlpNHSGTBBgPl WIcuNhyNaNOEFvL\r\n', 'output': ['NO\r\n']}, {'input': 'zyWvXBcUZqGqjHwZHQryBtFliLYnweXAoMKNpLaunaOlzaauWmLtywsEvWPiwxJapocAFRMjrqWJXYqfKEbBKnzLO\r\npsbi bsXpSeJaCkIuPWfSRADXdIClxcDCowwJzGCDTyAl\r\n', 'output': ['NO\r\n']}, {'input': 'kKhuIwRPLCwPFfcnsyCfBdnsraGeOCcLTfXuGjqFSGPSAeDZJSS bXKFanNqWjpFnvRpWxHJspvisDlADJBioxXNbVoXeUedoPcNEpUyEeYxdJXhGzFAmpAiHotSVwbZQsuWjIVhVaEGgqbZHIoDpiEmjTtFylCwCkWWzUOoUfOHxEZvDwNpXhBWamHn\r\nK VpJjGhNbwCRhcfmNGVjewBFpEmPlIKeTuWiukDtEWpjgqciqglkyNfWrBLbGAKvlNWxaUelJmSlSoakSpRzePvJsshOsTYrMPXdxKpaShjyVIXGhRIAdtiGpNwtiRmGTBZhkJqIMdxMHX RMxCMYcWjcjhtCHyFnCvjjezGbkRDRiVxkbh\r\n', 'output': ['NO\r\n']}, {'input': 'AXssNpFKyQmJcBdBdfkhhMUzfqJVgcLBddkwtnFSzSRUCjiDcdtmkzIGkCKSxWUEGhmHmciktJyGMkgCductyHx\r\nI nYhmJfPnvoKUiXYUBIPIcxNYTtvwPUoXERZvY ahlDpQFNMmVZqEBiYqYlHNqcpSCmhFczBlOAhsYFeqMGfqL EJsDNOgwoJfBzqijKOFcYQ\r\n', 'output': ['NO\r\n']}, {'input': 'lkhrzDZmkdbjzYKPNMRkiwCFoZsMzBQMnxxdKKVJezSBjnLjPpUYtabcPTIaDJeDEobbWHdKOdVfMQwDXzDDcSrwVenDEYpMqfiOQ xSsqApWnAMoyhQXCKFzHvvzvUvkWwmwZrvZz\r\nsUzGspYpRFsHRbRgTQuCBgnFgPkisTUfFNwyEEWWRiweWWgjRkVQxgTwxOzdsOwfrGIH O gCXpzvHzfItuEHaihmugEyymSJIogYwX qAwcwIItidfnzZDhZgQHi eRjMAeVkJHceDZuJkmxGowOsmcGYYvk Ajtgi TxwihvjLViNZjvscTWvsaQUelTSivLShhEl\r\n', 'output': ['NO\r\n']}, {'input': 'BRsVjyNhrqRHVwrJzuzRigEhdpbDmaACSPfed\r\nlWqKTjlrqOCUbgBBZdZDGCeQJDXawPnnDkQdZDgwrEQk\r\n', 'output': ['NO\r\n']}, {'input': 'KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw\r\nXZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk\r\n', 'output': ['NO\r\n']}]


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

import java.util.*;

public class Solution {

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

  public static void main(String[] args) {
    int n = sc.nextInt();
    int x = 1;
    for (int i = 1; i < n ;i++) {
      x += i;
      x %= n;
      System.out.print((x == 0 ? n : x) + " ");
    }
  }
}


Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.

The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:    0 ≤ plusi, minusi ≤ 50;  150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved;  300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved;  450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved;  600 ≤ di ≤ 2000 or di = 0, if problem D is not solved;  750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved.  All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).

Print on the single line the handle of the room leader.

NoteThe number of points that each participant from the example earns, are as follows:   Petr — 3860  tourist — 4140  Egor — 4030  c00lH4x0R —  - 350  some_participant — 2220 Thus, the leader of the room is tourist.

import java.util.*;

public class Trying
{
    public static void main (String[] args)
    {
        Scanner enter = new Scanner(System.in);
        int n = enter.nextInt(), scores [] = new int [n], pos = 0, max = Integer.MIN_VALUE;
        String handles[] = new String [n];
        for(int i = 0 ; i < n ; i++)
        {
            handles[i] = enter.next();
            scores[i] += (enter.nextInt()*100) - (enter.nextInt()*50)
            + enter.nextInt() + enter.nextInt() + enter.nextInt() + enter.nextInt() + enter.nextInt() ;
            if(scores[i] > max){max = scores[i]; pos = i;}
        }
        System.out.println(handles[pos]);
    }
}


Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($$$1, 2, 3, \ldots$$$). The node with a number $$$x$$$ ($$$x > 1$$$), is directly connected with a node with number $$$\frac{x}{f(x)}$$$, with $$$f(x)$$$ being the lowest prime divisor of $$$x$$$.Vanessa's mind is divided into $$$n$$$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $$$i$$$-th fragment is now located at the node with a number $$$k_i!$$$ (a factorial of $$$k_i$$$).To maximize the chance of successful awakening, Ivy decides to place the samples in a node $$$P$$$, so that the total length of paths from each fragment to $$$P$$$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $$$P$$$ needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $$$P$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — number of fragments of Vanessa's mind. The second line contains $$$n$$$ integers: $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), denoting the nodes where fragments of Vanessa's mind are located: the $$$i$$$-th fragment is at the node with a number $$$k_i!$$$.

Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $$$P$$$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $$$P$$$ needs to be counted multiple times as well.

NoteConsidering the first $$$24$$$ nodes of the system, the node network will look as follows (the nodes $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ are drawn bold):For the first example, Ivy will place the emotion samples at the node $$$1$$$. From here:  The distance from Vanessa's first fragment to the node $$$1$$$ is $$$1$$$.  The distance from Vanessa's second fragment to the node $$$1$$$ is $$$0$$$.  The distance from Vanessa's third fragment to the node $$$1$$$ is $$$4$$$. The total length is $$$5$$$.For the second example, the assembly node will be $$$6$$$. From here:  The distance from Vanessa's first fragment to the node $$$6$$$ is $$$0$$$.  The distance from Vanessa's second fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's third fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's fourth fragment to the node $$$6$$$ is again $$$2$$$. The total path length is $$$6$$$.

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

public class Akisolution {
	public static Scanner sc = new Scanner(System.in);
	public static PrintWriter out = new PrintWriter(System.out, true);
	public static final int MAXK = 5000;
	public static int n;
	public static int[] cnt = new int[MAXK + 1];
	public static int[][] primeExponential = new int[MAXK + 1][MAXK + 1];

	public static long min(long a, long b) {return ((a < b) ? a : b);}

	public static int max_element(int[] arr) {
		int res = -1000000000;
		for (int i=0; i<arr.length; i++) {
			if (arr[i] > res) res = arr[i];
		}
		return res;
	}

	public static int max_id(int[] arr) {
		int res = -1000000000, id = -1;
		for (int i=0; i<arr.length; i++) {
			if (arr[i] > res) {
				res = arr[i];
				id = i;
			}
		}
		return id;
	}

	public static void Preprocess() {
		for (int i=2; i<MAXK + 1; i++) {
			for (int j=0; j<MAXK + 1; j++) primeExponential[i][j] += primeExponential[i-1][j];
			int tmp = i;
			for (int x=2; x<=Math.sqrt(tmp); x++) {
				while (tmp % x == 0) {primeExponential[i][x]++; tmp /= x;}
			}
			if (tmp > 1) primeExponential[i][tmp]++;
		}
	}

	public static void Input() {
		n = sc.nextInt();
		for (int i=0; i<n; i++) {
			int k = sc.nextInt();
			cnt[k] += 1;
		}
	}

	public static void Solve() {
		Preprocess();

		int[] bestPD = new int[MAXK + 1];
		for (int i=0; i<MAXK + 1; i++) bestPD[i] = 1;
		long ans = 0, cur = 0;
		for (int i=1; i<MAXK + 1; i++) {
			if (cnt[i] == 0) {bestPD[i] = 1; continue;}
			for (int j=1; j<MAXK + 1; j++) {
				ans += (long)primeExponential[i][j] * cnt[i];
				cur += (long)primeExponential[i][j] * cnt[i];
				if (primeExponential[i][j] != 0) bestPD[i] = j;
			}
		}

		while (max_element(bestPD) > 1) {
			int[] frequency = new int[MAXK + 1];

			for (int i=0; i<MAXK + 1; i++) frequency[bestPD[i]] += cnt[i];

			int bestPrime = max_id(frequency);
			int bestGroup = frequency[bestPrime];
			if (bestGroup * 2 <= n) break;
			if (bestPrime == 1) break;
			cur -= bestGroup; cur += (n - bestGroup); ans = min(ans, cur);

			for (int i=0; i<MAXK + 1; i++) {
				if (bestPD[i] != bestPrime) bestPD[i] = 1;
				if (bestPD[i] == 1) continue;
				primeExponential[i][bestPD[i]] -= 1;
				while (bestPD[i] > 1 && primeExponential[i][bestPD[i]] == 0) bestPD[i]--;
			}
		}

		out.println(ans);
	}

	public static void main(String[] args) {
		Input(); Solve();
	}
}


This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

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

public final class Solution {

    private final static boolean USE_FILE_IO = false;

    Reader reader;
    Writer writer;

    Solution(Reader reader, Writer writer) {
        this.reader = reader;
        this.writer = writer;
    }

    long solve() throws java.lang.Exception {
        int n = reader.nextInt();
        int[] x = new int[n];
        int[] y = new int[n];
        for (int i=0; i<n; i++) {
            x[i] = reader.nextInt();
            y[i] = reader.nextInt();
        }
        long ans = 0;
        HashMap<Long, Integer> slopes = new HashMap<Long, Integer>();
        HashSet<Line> lines = new HashSet<Line>();
        for (int i=0; i<n-1; i++) {
            for (int j=i+1; j<n; j++) {
                Line line = new Line(x[i], y[i], x[j], y[j]);
                if (lines.add(line)) {
                    ans += (long)lines.size() - 1;
                    long slope = line.getSlope();
                    int count = slopes.getOrDefault(slope, 0);
                    ans -= (long)count;
                    slopes.put(slope, count + 1);
                }
            }
        }
        return ans;
    }

    class Line {
        int a, b, c;
        Line(int x1, int y1, int x2, int y2) {
            a = y2 - y1;
            b = x1 - x2;
            c = y1 * x2 - y2 * x1;
            if (a < 0 || (a==0 && b < 0)) {
                a = -a;
                b = -b;
                c = -c;
            }
            int gcd = gcd(gcd(Math.abs(a), Math.abs(b)), Math.abs(c));
            a /= gcd;
            b /= gcd;
            c /= gcd;
        }

        long getSlope() {
            return (long)a * 100000L + (long)b;
        }

        @Override
        public int hashCode() {
            return a ^ b ^ c;
        }

        @Override
        public boolean equals(Object o) {
            if (o == this) return true;
            if (o.getClass() != Line.class) return false;
            Line other = (Line) o;
            return other.a == this.a && other.b == this.b && other.c == this.c;
        }
    }

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

    public static void main(String[] args) throws java.lang.Exception {
        Reader reader = null;
        Writer writer = null;
        try {
            if (USE_FILE_IO) {
                reader = new Reader(new FileInputStream("input.txt"));
                writer = new Writer(new FileOutputStream("output.txt"));
            } else {
                reader = new Reader(System.in);
                writer = new Writer(System.out);
            }
            writer.writeLine(new Solution(reader, writer).solve());
        } finally {
            if (reader != null)
                reader.close();
            if (writer != null)
                writer.close();
        }
    }

    static class Writer {
        BufferedWriter bw;

        public Writer(OutputStream out) {
            bw = new BufferedWriter(new OutputStreamWriter(out));
        }

        void write(String s) throws java.lang.Exception {
            bw.write(s);
        }

        void write(int x) throws java.lang.Exception {
            write(String.valueOf(x));
        }

        void write(long x) throws java.lang.Exception {
            write(String.valueOf(x));
        }

        void write(char c) throws java.lang.Exception {
            bw.write(c);
        }

        void newLine() throws java.lang.Exception {
            bw.newLine();
        }

        void writeLine(String s) throws java.lang.Exception {
            write(s);
            newLine();
        }

        void writeLine(int n) throws java.lang.Exception {
            writeLine(String.valueOf(n));
        }

        void writeLine(long n) throws java.lang.Exception {
            writeLine(String.valueOf(n));
        }

        void writeLine() throws java.lang.Exception {
            writeLine("");
        }

        void close() throws java.lang.Exception {
            bw.flush();
            bw.close();
        }
    }

    static class Reader {
        BufferedReader br;
        StringTokenizer st;

        public Reader(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
        }

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

        String[] nextTokens(int n) {
            String[] a = new String[n];
            for (int i=0; i<n; i++) {
                a[i] = nextToken();
            }
            return a;
        }

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

        int[] nextInts(int n) {
            int[] a = new int[n];
            for (int i=0; i<n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

        long[] nextLongs(int n) {
            long[] a = new long[n];
            for (int i=0; i<n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

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

        void close() throws java.lang.Exception {
            br.close();
        }
    }
}


Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.

NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete.

import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner sc = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] arr = new int[n];
        for (int i=0; i<n; ++i){
            arr[i] = Integer.parseInt(st.nextToken())%2;
        }
        int[] zz = new int[n];
        for (int i=0; i<n; ++i)
            zz[i] = arr[i]^1;
        int ans = solve(arr,n);
        ans |= solve(zz,n);
        System.out.println(ans==1?"YES":"NO");
        sc.close();
        br.close();
        bw.close();
    }

    public static int solve(int[] arr, int n){
        Stack<Integer> stack = new Stack<>();
        for (int i=0; i<n; ++i){
            if (stack.isEmpty())
                stack.add(arr[i]);
            else {
                if (arr[i] > stack.peek()){
                    stack.add(arr[i]);
                } else if (arr[i] == stack.peek())
                    stack.pop();
                else stack.add(arr[i]);
            }
        }
        if (stack.size() > 1){
            return 0;
        }
        return 1;
    }

}


Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200\,000$$$, $$$2 \le k \le n$$$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

Print the minimum possible break in minutes between eating chocolate bars.

NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        String abil = sc.nextLine();
        abil = sc.nextLine();
        ArrayList<Integer> pos = new ArrayList<>();
        for(int i = 1; i < abil.length(); ++i)
            if (abil.charAt(i) == '0')
                pos.add(i);
        int l = -1, r = n+1;
        while (r - l > 1)
        {
            int m = (l + r) / 2;
            int last = 0;
            int left = k - 1;
            boolean ok = true;
            for(int i = 0; i < pos.size(); ++i)
                if (i == pos.size()-1 || last + m + 1 < pos.get(i+1))
                {
                    ok = ok && pos.get(i) - last <= m+1;
                    last = pos.get(i);
                    --left;
                }
            if (left < 0 || !ok)
                l = m;
            else
                r = m;
        }
        System.out.println(r);
    }
}


In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;

/* Name of the class has to be "Main" only if the class is public*/
public class CF602C
{
    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

    static class Node {

        long pp;
        long a, b;

        Node(long x, long y) {
            a = x;
            b = y;
            pp = a * b;
        }
    }
    static class Comp implements Comparator<Node> {

        public int compare(Node o1, Node o2) {
            if (o1.pp > o2.pp) {
                return 1;
            } else {
                return -1;
            }
        }
    }
    public static void main(String[] args) {
        FastReader sc=new FastReader();
        PrintWriter out=new PrintWriter(System.out);
        //your code starts here
        int n=sc.nextInt();
        boolean adj[][]=new boolean[n][n];
        int m=sc.nextInt();
        for(int i=0;i<m;i++)
        {
            int a=sc.nextInt()-1;
            int b=sc.nextInt()-1;
            // adding edges of undirected graph
            adj[a][b]=true; adj[b][a]=true;
        }
        if(m==0 || m==(n*(n-1)/2)) {
            out.println(-1); out.close(); return;
        }
        int[] dist=new int[n]; Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0]=0;
        Queue<Integer> q=new LinkedList();
        q.add(0);
        while(!q.isEmpty())
        {
            int s=q.poll();
            for(int i=0;i<n;i++)
            {
                if(!adj[0][n-1] && adj[s][i])
                {
                    if(dist[i]==Integer.MAX_VALUE) {
                    dist[i]=dist[s]+1;
                    q.add(i);
                    }
                }
                else if(!adj[s][i] && adj[0][n-1])
                {
                    if(dist[i]==Integer.MAX_VALUE)
                    {
                        dist[i]=dist[s]+1;
                        q.add(i);
                    }
                }
            }
        }
        //for(int i:dist) out.print(i+" ");
         if(dist[n-1]==Integer.MAX_VALUE) out.println(-1);
         else out.println(Math.max(1,dist[n-1]));
        out.close();
    }
}


Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A·B·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B и C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.

The only line contains integer n from the problem's statement (1 ≤ n ≤ 109).

Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.

import java.util.*;

public class HelpFarmer {

    static long find(long x, long y, long z) {
        long A = x + 1;
        long B = y + 2;
        long C = z + 2;

        return A * B * C - x * y * z;
    }

    static void find(long x, long yz, long[] minmax) {
        for (int y = 1; y <= yz / y; y++) {
            if (yz % y == 0) {
                long z = yz / y;
                long ans = find(x, y, z);
                minmax[0] = Math.min(minmax[0], ans);
                minmax[1] = Math.max(minmax[1], ans);
            }
        }
    }

    static long[] solve(long n) {
        long[] minmax = {Long.MAX_VALUE, Long.MIN_VALUE};
        for (long x = 1; x <= n / x; x++) {
            if (n % x == 0) {
                long yz = n / x;
                find(x, yz, minmax);
                find(yz, x, minmax);
            }
        }
        return minmax;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        long n = in.nextInt();
        long[] ans = solve(n);
        System.out.println(ans[0] + " " + ans[1]);

        in.close();
        System.exit(0);
    }
}