import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class TVSubscriptionsB extends PrintWriter {
    //this trick improves performances
    TVSubscriptionsB() {
        super(System.out);
    }

    public static void main(String[] $) {
        TVSubscriptionsB o = new TVSubscriptionsB();
        o.main();
        o.flush();
    }

    void main() {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        //use this if just a single test
        //int count = 1;
        while (count-- > 0) {
            final int n = sc.nextInt();
            final int k = sc.nextInt();
            final int d = sc.nextInt();
            final int[] shows = new int[n];
            for (int i = 0; i < n; i++) {
                shows[i]=sc.nextInt();
            }
            int min=Integer.MAX_VALUE;
            for (int i = 0; i <= n-d; i++) {
                final HashSet<Integer> set = new HashSet<>();
                for (int j = 0; j < d ; j++) {
                    set.add(shows[i+j]);
                    if(set.size()>min){
                        break;
                    }
                }
                min=Math.min(min, set.size());
            }
            println(min);
        }
        sc.close();
    }
}

The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.

Print $$$t$$$ integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.

NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.

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

public class Main {

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

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            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 char nextChar() {
            return next().charAt(0);
        }

        public float nextFloat() {
            return Float.parseFloat(next());
        }

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

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

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

    static class Task {

        public static int q, n, k, d;
        public static int[] N = new int[200005];
        public static int[] check = new int[1000005];

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int q = in.nextInt();
            while (q-- > 0) {
                n = in.nextInt();
                k = in.nextInt();
                d = in.nextInt();
                int count = 0;
                int mi = Integer.MAX_VALUE;
                for (int i = 0; i < d - 1; i++) {
                    N[i] = in.nextInt() - 1;
                    if (check[N[i]] == 0) {
                        count++;
                    }
                    check[N[i]]++;
                }
                for (int i = d - 1; i < n; i++) {
                    N[i] = in.nextInt() - 1;
                    if (check[N[i]] == 0) {
                        count++;
                    }
                    check[N[i]]++;
                    if (count < mi) {
                        mi = count;
                    }
                    if (check[N[i - d + 1]] == 1) {
                        count--;
                    }
                    check[N[i - d + 1]]--;
                }
                out.println(mi);
                for (int i = n - d + 1; i < n; i++) {
                    check[N[i]]--;
                }
            }
        }
    }
}


import java.util.Locale;
import java.util.Scanner;

public class ProblemA {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int b = sc.nextInt();
        int[] ns = new int[n];
        float[] cs = new float[n];
        int max = 0;
        boolean found = true;
        for (int i = 0; i < n; i++) {
            ns[i] = sc.nextInt();
            max = Math.max(max, ns[i]);
        }
        for (int i = 0; i < n; i++) {
            cs[i] = max - ns[i];
            b -= cs[i];
            if (b < 0) {
                found = false;
                break;
            }
        }
        if(found){
            for(int i = 0; i< n;i++){
                System.out.println(String.format(Locale.ENGLISH, "%1$.6f", cs[i] + b / n));
            }
        }
        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);
    }
}


import java.util.Scanner;
import java.util.Arrays;
public class DomainPilling
{
    public static void main(String[]args){
        Scanner input=new Scanner(System.in);
        int t=input.nextInt();
        int i,out,j;
        out=1;
        int counter=1;
        for(i=0;i<t-1,i++){
            out+=counter;
            for(j=0;out>t;j++){
                out-=j*t;
            }
            System.out.print(out+" ");
            counter+=1;

        }
        System.out.println();

    }
}

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


import java.util.*;
public class SysadminBob
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		String s=sc.next();
		int flag=0;
		StringBuffer stb=new StringBuffer(s);
		if(s.charAt(0)=='@' || s.indexOf('@')==-1)
		{
			System.out.println("No solution");
		}

		else
		{
			int k=0;
			for(int i=0;i<s.length();i++)
			{

				int temp=s.indexOf('@',k);
				if(temp==-1 || s.indexOf('@',temp+1)==-1)
				{
					break;
				}
//				System.out.println("temp:"+temp);
//				System.out.println("temp+2:" +(temp+2));
				stb.insert(temp+2, ',');
				s=stb.toString();
				k=temp+1;
				i=k;
			}
		//	System.out.println(s);

			for(int i=0;i<s.length();i++)
			{
				if((s.charAt(i)=='@' && s.charAt(i-1)==',') ||( s.charAt(i)=='@' && s.charAt(i+1)=='@' ))
				{
					System.out.println("No solution");
					flag=1;
					break;
				}
			}
			if(flag==0)
			{
				if(s.charAt(s.length()-1)==',')
				{
					System.out.println(s.substring(0,s.length()-1));
				}

				else
				{
					System.out.println(s);
				}
			}
		}
	}
}

Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.

The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters «@».

If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.

import java.util.*;
public class SysadminBob
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		String s=sc.next();
		int flag=0;
		StringBuffer stb=new StringBuffer(s);
		if(s.charAt(0)=='@' || s.indexOf('@')==-1 || s.charAt(s.length()-1)=='@')
		{
			System.out.println("No solution");
		}

		else
		{
			int k=0;
			for(int i=0;i<s.length();i++)
			{

				int temp=s.indexOf('@',k);
				if(temp==-1 || s.indexOf('@',temp+1)==-1)
				{
					break;
				}
//				System.out.println("temp:"+temp);
//				System.out.println("temp+2:" +(temp+2));
				stb.insert(temp+2, ',');
				s=stb.toString();
				k=temp+1;
				i=k;
			}
		//	System.out.println(s);

			for(int i=0;i<s.length();i++)
			{
				if((s.charAt(i)=='@' && s.charAt(i-1)==',') ||( s.charAt(i)=='@' && s.charAt(i+1)=='@' ))
				{
					System.out.println("No solution");
					flag=1;
					break;
				}
			}
			if(flag==0)
			{
				if(s.charAt(s.length()-1)==',')
				{
					System.out.println(s.substring(0,s.length()-1));
				}

				else
				{
					System.out.println(s);
				}
			}
		}
	}
}

[{'input': 'a@aa@a\r\n', 'output': ['a@a,a@a\r\n']}, {'input': 'a@a@a\r\n', 'output': ['No solution\r\n']}, {'input': '@aa@a\r\n', 'output': ['No solution\r\n']}, {'input': 'aba@caba@daba\r\n', 'output': ['aba@c,aba@daba\r\n']}, {'input': 'asd@qwasd@qwasd@qwasd@qwasd@qw\r\n', 'output': ['asd@q,wasd@q,wasd@q,wasd@q,wasd@qw\r\n']}, {'input': 'qwer@ty\r\n', 'output': ['qwer@ty\r\n']}, {'input': '@\r\n', 'output': ['No solution\r\n']}, {'input': 'g\r\n', 'output': ['No solution\r\n']}, {'input': '@@\r\n', 'output': ['No solution\r\n']}, {'input': '@@@\r\n', 'output': ['No solution\r\n']}, {'input': 'r@@\r\n', 'output': ['No solution\r\n']}, {'input': '@@r\r\n', 'output': ['No solution\r\n']}, {'input': '@r@\r\n', 'output': ['No solution\r\n']}, {'input': 'w@\r\n', 'output': ['No solution\r\n']}, {'input': '@e\r\n', 'output': ['No solution\r\n']}, {'input': 'jj\r\n', 'output': ['No solution\r\n']}, {'input': '@gh\r\n', 'output': ['No solution\r\n']}, {'input': 'n@m\r\n', 'output': ['n@m\r\n']}, {'input': 'kl@\r\n', 'output': ['No solution\r\n']}, {'input': 'fpm\r\n', 'output': ['No solution\r\n']}, {'input': '@@@@\r\n', 'output': ['No solution\r\n']}, {'input': 'q@@@\r\n', 'output': ['No solution\r\n']}, {'input': '@d@@\r\n', 'output': ['No solution\r\n']}, {'input': '@@v@\r\n', 'output': ['No solution\r\n']}, {'input': '@@@c\r\n', 'output': ['No solution\r\n']}, {'input': '@@zx\r\n', 'output': ['No solution\r\n']}, {'input': '@x@a\r\n', 'output': ['No solution\r\n']}, {'input': '@pq@\r\n', 'output': ['No solution\r\n']}, {'input': 'w@@e\r\n', 'output': ['No solution\r\n']}, {'input': 'e@s@\r\n', 'output': ['No solution\r\n']}, {'input': 'ec@@\r\n', 'output': ['No solution\r\n']}, {'input': '@hjk\r\n', 'output': ['No solution\r\n']}, {'input': 'e@vb\r\n', 'output': ['e@vb\r\n']}, {'input': 'tg@q\r\n', 'output': ['tg@q\r\n']}, {'input': 'jkl@\r\n', 'output': ['No solution\r\n']}, {'input': 'werb\r\n', 'output': ['No solution\r\n']}, {'input': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n', 'output': ['No solution\r\n']}, {'input': '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n', 'output': ['No solution\r\n']}, {'input': 'duk@rufrxjzqbwkfrzf@sjp@mdpyrokdfmcmexxtjqaalruvtzwfsqabi@tjkxilrhkwzfeuqm@lpwnxgebirdvwplsvrtxvhmzv\r\n', 'output': ['duk@r,ufrxjzqbwkfrzf@s,jp@m,dpyrokdfmcmexxtjqaalruvtzwfsqabi@t,jkxilrhkwzfeuqm@lpwnxgebirdvwplsvrtxvhmzv\r\n']}, {'input': 'umegsn@qlmkpkyrmuclefdpfhzuhyjcoqthnvpwzhkwrdvlzfbrqpzlg@ebzycyaofyyetwcepe@nxjwyeaqbuxxbohfzrnmebuy\r\n', 'output': ['umegsn@q,lmkpkyrmuclefdpfhzuhyjcoqthnvpwzhkwrdvlzfbrqpzlg@e,bzycyaofyyetwcepe@nxjwyeaqbuxxbohfzrnmebuy\r\n']}, {'input': 'l@snuoytgflrtuexpx@txzhhdwbakfhfro@syxistypegfvdmurvuubrj@grsznzhcotagqueuxtnjgfaywzkbglwwiptjyocxcs\r\n', 'output': ['l@s,nuoytgflrtuexpx@t,xzhhdwbakfhfro@s,yxistypegfvdmurvuubrj@grsznzhcotagqueuxtnjgfaywzkbglwwiptjyocxcs\r\n']}, {'input': 'crvjlke@yqsdofatzuuspt@@uumdkiwhtg@crxiabnujfmcquylyklxaedniwnq@@f@@rfnsjtylurexmdaaykvxmgeij@jkjsyi\r\n', 'output': ['No solution\r\n']}, {'input': 'ukpcivvjubgalr@bdxangokpaxzxuxe@qlemwpvywfudffafsqlmmhhalaaolktmgmhmrwvkdcvwxcfbytnz@jgmbhpwqcmecnxc\r\n', 'output': ['ukpcivvjubgalr@b,dxangokpaxzxuxe@q,lemwpvywfudffafsqlmmhhalaaolktmgmhmrwvkdcvwxcfbytnz@jgmbhpwqcmecnxc\r\n']}, {'input': 'mehxghlvnnazggvpnjdbchdolqguiurrfghwxpwhphdbhloltwnnqovsnsdmfevlikmrlvwvkcqysefvoraorhamchghqaooxaxz\r\n', 'output': ['No solution\r\n']}, {'input': 'whazbewtogyre@wqlsswhygx@osevwzytuaukqpp@gfjbtwnhpnlxwci@ovaaat@ookd@@o@bss@wyrrwzysubw@utyltkk@hlkx\r\n', 'output': ['No solution\r\n']}, {'input': 'vpulcessdotvylvmkeonzbpncjxaaigotkyvngsbkicomikyavpsjcphlznjtdmvbqiroxvfcmcczfmqbyedujvrupzlaswbzanv\r\n', 'output': ['No solution\r\n']}, {'input': 'mhxapzklriiincpnysmegjzaxdngifbowkzivvgisqbekprdmdoqezdsrsrwwmht@hwywjqflvqdevpqisncwbftlttfkgsyetop\r\n', 'output': ['mhxapzklriiincpnysmegjzaxdngifbowkzivvgisqbekprdmdoqezdsrsrwwmht@hwywjqflvqdevpqisncwbftlttfkgsyetop\r\n']}, {'input': 'dxzqftcghawwcwh@iepanbiclstbsxbrsoep@@jwhrptgiu@zfykoravtaykvkzseqfnlsbvjnsgiajgjtgucvewlpxmqwvkghlo\r\n', 'output': ['No solution\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtgh@\r\n', 'output': ['No solution\r\n']}, {'input': '@rierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'e@ierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['e@ierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtg@d\r\n', 'output': ['erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtg@d\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjt@h@\r\n', 'output': ['No solution\r\n']}, {'input': '@r@erjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'e@i@rjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierj@g@d\r\n', 'output': ['No solution\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtg@@\r\n', 'output': ['No solution\r\n']}, {'input': '@@ierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'e@@erjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'erierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjt@@d\r\n', 'output': ['No solution\r\n']}, {'input': 'erierjtghderierjtghderierj@@dderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghd\r\n', 'output': ['No solution\r\n']}, {'input': 'a@rierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderirjtghderierjtghderierjtghderierjthderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtgh@a\r\n', 'output': ['a@r,ierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderirjtghderierjtghderierjtghderierjthderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtghderierjtgh@a\r\n']}, {'input': 'd@nt@om@zz@ut@tr@ta@ap@ou@sy@sv@fg@el@rp@qr@nl@j\r\n', 'output': ['d@n,t@o,m@z,z@u,t@t,r@t,a@a,p@o,u@s,y@s,v@f,g@e,l@r,p@q,r@n,l@j\r\n']}, {'input': 'a@mc@ks@gu@rl@gq@zq@iz@da@uq@mi@nf@zs@hi@we@ej@ke@vb@az@yz@yl@rr@gh@um@nv@qe@qq@de@dy@op@gt@vx@ak@q\r\n', 'output': ['a@m,c@k,s@g,u@r,l@g,q@z,q@i,z@d,a@u,q@m,i@n,f@z,s@h,i@w,e@e,j@k,e@v,b@a,z@y,z@y,l@r,r@g,h@u,m@n,v@q,e@q,q@d,e@d,y@o,p@g,t@v,x@a,k@q\r\n']}, {'input': 'c@ir@xf@ap@fk@sp@wm@ec@qw@vg@by@iu@tr@wu@pv@lj@dd@tc@qj@ok@hm@bs@ul@ez@cg@ht@xf@ag@tr@hz@ap@tx@ly@dg@hu@nd@uv@il@ii@cn@nc@nb@cy@kp@dk@xa@da@ta@yr@yv@qg@db@je@wz@rn@yh@xi@mj@kc@uj@yu@cf@ps@ao@fo@le@d\r\n', 'output': ['c@i,r@x,f@a,p@f,k@s,p@w,m@e,c@q,w@v,g@b,y@i,u@t,r@w,u@p,v@l,j@d,d@t,c@q,j@o,k@h,m@b,s@u,l@e,z@c,g@h,t@x,f@a,g@t,r@h,z@a,p@t,x@l,y@d,g@h,u@n,d@u,v@i,l@i,i@c,n@n,c@n,b@c,y@k,p@d,k@x,a@d,a@t,a@y,r@y,v@q,g@d,b@j,e@w,z@r,n@y,h@x,i@m,j@k,c@u,j@y,u@c,f@p,s@a,o@f,o@l,e@d\r\n']}, {'input': 'm@us@ru@mg@rq@ed@ot@gt@fo@gs@lm@cx@au@rq@zt@zk@jr@xd@oa@py@kf@lk@zr@ko@lj@wv@fl@yl@gk@cx@px@kl@ic@sr@xn@hm@xs@km@tk@ui@ya@pa@xx@ze@py@ir@xj@cr@dq@lr@cm@zu@lt@bx@kq@kx@fr@lu@vb@rz@hg@iw@dl@pf@pl@wv@z\r\n', 'output': ['m@u,s@r,u@m,g@r,q@e,d@o,t@g,t@f,o@g,s@l,m@c,x@a,u@r,q@z,t@z,k@j,r@x,d@o,a@p,y@k,f@l,k@z,r@k,o@l,j@w,v@f,l@y,l@g,k@c,x@p,x@k,l@i,c@s,r@x,n@h,m@x,s@k,m@t,k@u,i@y,a@p,a@x,x@z,e@p,y@i,r@x,j@c,r@d,q@l,r@c,m@z,u@l,t@b,x@k,q@k,x@f,r@l,u@v,b@r,z@h,g@i,w@d,l@p,f@p,l@w,v@z\r\n']}, {'input': 'gjkjqjrks@eyqiia@qfijelnmigoditxjrtuhukalfl@nmwancimlqtfekzkxgjioedhtdivqajwbmu@hpdxuiwurpgenxaiqaqkcqimcvitljuisfiojlylveie@neqdjzeqdbiatjpuhujgykl@gmmlrhnlghsoeyrccygigtkjrjxdwmnkouaiaqpquluwcdqlxqb\r\n', 'output': ['gjkjqjrks@e,yqiia@q,fijelnmigoditxjrtuhukalfl@n,mwancimlqtfekzkxgjioedhtdivqajwbmu@h,pdxuiwurpgenxaiqaqkcqimcvitljuisfiojlylveie@n,eqdjzeqdbiatjpuhujgykl@gmmlrhnlghsoeyrccygigtkjrjxdwmnkouaiaqpquluwcdqlxqb\r\n']}, {'input': 'uakh@chpowdmvdywosakyyknpriverjjgklmdrgwufpawgvhabjbnemimjktgbkx@fzvqcodbceqnihl@kpsslhwwndad@@yavjafrwkqyt@urhnwgnqamn@xkc@vngzlssmtheuxkpzjlbbjq@mwiojmvpilm@hlrmxheszskhxritsieubjjazrngxlqeedfkiuwny\r\n', 'output': ['No solution\r\n']}, {'input': 'usmjophufnkamnvowbauu@wfoyceknkgeaejlbbqhtucbl@wurukjezj@irhdgrfhyfkz@fbmqgxvtxcebztirvwjf@fnav@@f@paookujny@z@fmcxgvab@@kpqbwuxxwxhsrbivlbunmdjzk@afjznrjjtkq@cafetoinfleecjqvlzpkqlspoufwmidvoblti@jbg\r\n', 'output': ['No solution\r\n']}, {'input': 'axkxcgcmlxq@v@ynnjximcujikloyls@lqvxiyca@feimaioavacmquasneqbrqftknpbrzpahtcc@ijwqmyzsuidqkm@dffuiitpugbvty@izbnqxhdjasihhlt@gjrol@vy@vnqpxuqbofzzwl@toywomxopbuttczszx@fuowtjmtqy@gypx@la@@tweln@jgyktb\r\n', 'output': ['No solution\r\n']}, {'input': 'mplxc@crww@gllecngcsbmxmksrgcb@lbrcnkwxclkcgvfeqeoymproppxhxbgm@q@bfxxvuymnnjolqklabcinwpdlxj@jcevvilhmpyiwggvlmdanfhhlgbkobnmei@bvqtdq@osijfdsuouvcqpcjxjqiuhgts@xapp@cpqvlhlfrxtgunbbjwhuafovbcbqyhmlu\r\n', 'output': ['No solution\r\n']}, {'input': 'aglvesxsmivijisod@mxcnbfcfgqfwjouidlsueaswf@obehqpvbkmukxkicyoknkbol@kutunggpoxxfpbe@qkhv@llddqqoyjeex@byvtlhbifqmvlukmrvgvpwrscwfhpuwyknwchqhrdqgarmnsdlqgf@lseltghg@bhuwbfjpsvayzk@fvwow@zapklumefauly\r\n', 'output': ['aglvesxsmivijisod@m,xcnbfcfgqfwjouidlsueaswf@o,behqpvbkmukxkicyoknkbol@k,utunggpoxxfpbe@q,khv@l,lddqqoyjeex@b,yvtlhbifqmvlukmrvgvpwrscwfhpuwyknwchqhrdqgarmnsdlqgf@l,seltghg@b,huwbfjpsvayzk@f,vwow@zapklumefauly\r\n']}, {'input': 'gbllovyerhudm@aluhtnstcp@uwgvejnmqpt@nez@ltzqjrcgwkkpzicb@ihh@wldhvjbrl@efbdzbeg@zyovsta@n@c@jutail@nclsbcihabzr@snowxeyl@jewen@aduffvhr@ifufzzt@i@kptygveumwaknmrn@edsapqpcwsqypmutggztum@ewzakeamobzxt\r\n', 'output': ['No solution\r\n']}, {'input': 'dokshhqwmtbefrynupvusfxroggoqkjqfyabzkbccjmavumncorbcoairybeknhnpnwftrlbopsvqlgjbrowmfmoeebqseneabvgbcxmujmcqomoawrooixmqmyspfgafudfdfyrnujhgnbtsehgsnvdztjdpnskyquwdtkbfjtvrfjcqzmourvqsnfgjfqjgndydpch\r\n', 'output': ['No solution\r\n']}, {'input': 'jrlhtwmotdhtgcqokodparuqypwlkbhfsxvmdpfiraokekrolwtlsqjzcuvjfnvblznyngasauzln@gjypvjcwljnotgjlxketfgtntbotwjehea@vppouyoujujlhjrxbhvltfdslaqwynwjefbdbnuehmipqmtsrivlnippgftgnkhdgqiqbfvgrtoxrznncncqcvf\r\n', 'output': ['jrlhtwmotdhtgcqokodparuqypwlkbhfsxvmdpfiraokekrolwtlsqjzcuvjfnvblznyngasauzln@g,jypvjcwljnotgjlxketfgtntbotwjehea@vppouyoujujlhjrxbhvltfdslaqwynwjefbdbnuehmipqmtsrivlnippgftgnkhdgqiqbfvgrtoxrznncncqcvf\r\n']}, {'input': 'oxkvgnggznlfhminxkkhictpiaokdsfrewnxiujpjpstlyxovfwugrsqnpooalknjnfugxojozizlicwvnbflhdevpvnvwztnfiapairpigexbaeshondqdecduewmfrxunphikvlfwmrpsxrhxyjlsgqfiaqnwzlzxcyuudhzr@twllmhyfclybxqazhrmxdtokxawc\r\n', 'output': ['oxkvgnggznlfhminxkkhictpiaokdsfrewnxiujpjpstlyxovfwugrsqnpooalknjnfugxojozizlicwvnbflhdevpvnvwztnfiapairpigexbaeshondqdecduewmfrxunphikvlfwmrpsxrhxyjlsgqfiaqnwzlzxcyuudhzr@twllmhyfclybxqazhrmxdtokxawc\r\n']}]


import java.util.Scanner;

public class CF185A {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        long result = 1;
        for(long i = 0; i < n; i++){
            result = result*3;
            if(i>=1){
                result += (n-1);
            }
        }
        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;
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        String N = kb.nextLine();
        StringBuilder sb = new StringBuilder(N);
        for(int i = 0; i < sb.length(); i++) {
            if(sb.charAt(i) == ' ') {
                if(sb.charAt(i+1) == ' ') {
                    sb.deleteCharAt(i+1);
                    i--;
                    continue;
                }
            }
            if(sb.charAt(i) == ',' || sb.charAt(i) == ',' || sb.charAt(i) == '!' || sb.charAt(i) == '?') {
                if(sb.charAt(i+1) != ' ') {
                    sb.insert(i+1, ' ');
                }
                if(sb.charAt(i-1) == ' ') {
                    sb.deleteCharAt(i-1);
                    i--;
                }
            }
        }
        System.out.println(sb.toString());
    }
}

You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules:  if there is no punctuation mark between two words, then they should be separated by exactly one space  there should be no spaces before each punctuation mark  there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.

The input data contains of a single non-empty line — the text whose length is no more than 10000 characters.

Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.

import java.util.*;

public class code{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // String a = scan.nextLine();
        // // long b = scan.nextLong();
        // long temp;
        // if(a>b){
        //     temp = a;
        //     a = b;
        //     b = temp;
        // }
        // scan.close();
        // long gcd = GCD(a,b);
        // long lcm = (a*b)/gcd;
        // System.out.println("GCD : "+gcd+"\nLCM : "+lcm);
        String s = scan.nextLine();
        s = s.replaceAll("\\s{2,}", " ").trim();
        s = s.replace(".", " .");
        s = s.replace(",", " ,");
        s = s.replace("!", " !");
        s = s.replace("?", " ?");
        s = s.replaceAll("\\s{2,}", " ").trim();
        s = s.replace(" .", ". ");
        s = s.replace(" ,", ", ");
        s = s.replace(" !", "! ");
        s = s.replace(" ?", "? ");
        s = s.replaceAll("\\s{2,}", " ").trim();
        System.out.println(s);

        // s = s.replaceAll(/[.,?!]/, /[.,?!] /);
        // s = s.replaceAll("  ", " ");
        // s = s.replaceAll(/[.,?!]/,  /[,.?!]/);
        // s = s.replaceAll(/[.,?!]  /, /[.,?!]/);

    }
}

[{'input': 'galileo galilei was an   italian physicist  ,mathematician,astronomer\r\n', 'output': ['galileo galilei was an italian physicist, mathematician, astronomer\r\n']}, {'input': 'galileo  was  born  in  pisa\r\n', 'output': ['galileo was born in pisa\r\n']}, {'input': 'jkhksdfhsdfsf\r\n', 'output': ['jkhksdfhsdfsf\r\n']}, {'input': 'a a a a a\r\n', 'output': ['a a a a a\r\n']}, {'input': 'ksdfk sdlfsdf sdf sdf sdf\r\n', 'output': ['ksdfk sdlfsdf sdf sdf sdf\r\n']}, {'input': 'gdv\r\n', 'output': ['gdv\r\n']}, {'input': 'incen q\r\n', 'output': ['incen q\r\n']}, {'input': 'k  ?   gq    dad\r\n', 'output': ['k? gq dad\r\n']}, {'input': 'ntomzzut  !pousysvfg ,rnl   mcyytihe     hplnqnb\r\n', 'output': ['ntomzzut! pousysvfg, rnl mcyytihe hplnqnb\r\n']}, {'input': 'mck  . gq   dauqminf      wee   bazyzy     humnv    d pgtvx  , vxntxgrkrc    rg    rwr,  uuyweyz  l\r\n', 'output': ['mck. gq dauqminf wee bazyzy humnv d pgtvx, vxntxgrkrc rg rwr, uuyweyz l\r\n']}, {'input': 'jjcmhwnon   taetfgdvc,  ysrajurstj !   fryavybwpg  hnxbnsron ,txplbmm atw?wkfhn  ez  mcdn     tujsy      wrdhw   . k  i lzwtxcyam     fi  .  nyeu j\r\n', 'output': ['jjcmhwnon taetfgdvc, ysrajurstj! fryavybwpg hnxbnsron, txplbmm atw? wkfhn ez mcdn tujsy wrdhw. k i lzwtxcyam fi. nyeu j\r\n']}, {'input': 'chcf  htb flfwkosmda    a    qygyompixkgz  ?rg?  hdw   f   dsvqzs     kxvjt ?  zj    zghgarwihw   zgrhr  xlwmhv   .  lycpsmdm    iotv  .   d jhsxoogbr  !   ppgrpwcrcl      inw usegrtd  ?fexma ?   mhszrvdoa   ,audsrhina  epoleuq     oaz   hqapedl   lm\r\n', 'output': ['chcf htb flfwkosmda a qygyompixkgz? rg? hdw f dsvqzs kxvjt? zj zghgarwihw zgrhr xlwmhv. lycpsmdm iotv. d jhsxoogbr! ppgrpwcrcl inw usegrtd? fexma? mhszrvdoa, audsrhina epoleuq oaz hqapedl lm\r\n']}, {'input': 'cutjrjhf x  megxzdtbrw   bq!drzsvsvcdd ukydvulxgz! tmacmcwoay   xyyx   v   ajrhsvxm  sy   boce    kbpshtbija    phuxfhw      hfpb   do  ? z    yb  aztpydzwjf. fjhihoei  !oyenq !heupilvm  whemii     mtt      kbjh      hvtfv   pr  , s , h    swtdils  jcppog . nyl   ?   zier  is  ?  xibbv   exufvjjgn.  yiqhmrp     opeeimxlmv      krxa  crc    czqwnka   psfsjvou   nywayqoec  .t ,  kjtpg  d  ?b  ?   zb\r\n', 'output': ['cutjrjhf x megxzdtbrw bq! drzsvsvcdd ukydvulxgz! tmacmcwoay xyyx v ajrhsvxm sy boce kbpshtbija phuxfhw hfpb do? z yb aztpydzwjf. fjhihoei! oyenq! heupilvm whemii mtt kbjh hvtfv pr, s, h swtdils jcppog. nyl? zier is? xibbv exufvjjgn. yiqhmrp opeeimxlmv krxa crc czqwnka psfsjvou nywayqoec. t, kjtpg d? b? zb\r\n']}, {'input': 'ajdwlf  ibvlfqadt sqdn      aoj   nsjtivfrsp  !mquqfgzrbp    w ow aydap   ry     s  .   jwlvg  ?   ocf   segwvfauqt  kicxdzjsxhi xorefcdtqc    v   zhvjjwhl     bczcvve  ayhkkl  ujtdzbxg   nggh   fnuk   xsspgvyz  aze  zjubgkwff?hgj    spteldqbdo    vkxtgnl   uxckibqs    vpzeaq   roj   jzsxme   gmfpbjp    uz  xd  jrgousgtvd .  muozgtktxi   ! c   .  vdma   hzhllqwg .   daq?  rhvp     shwrlrjmgx     ggq    eotbiqlcse   . rfklcrpzvw   ?ieitcaby   srinbwso gs  oelefwq xdctsgxycn     yxbbusqe.eyd  .zyo\r\n', 'output': ['ajdwlf ibvlfqadt sqdn aoj nsjtivfrsp! mquqfgzrbp w ow aydap ry s. jwlvg? ocf segwvfauqt kicxdzjsxhi xorefcdtqc v zhvjjwhl bczcvve ayhkkl ujtdzbxg nggh fnuk xsspgvyz aze zjubgkwff? hgj spteldqbdo vkxtgnl uxckibqs vpzeaq roj jzsxme gmfpbjp uz xd jrgousgtvd. muozgtktxi! c. vdma hzhllqwg. daq? rhvp shwrlrjmgx ggq eotbiqlcse. rfklcrpzvw? ieitcaby srinbwso gs oelefwq xdctsgxycn yxbbusqe. eyd. zyo\r\n']}, {'input': 'x\r\n', 'output': ['x\r\n']}, {'input': 'xx\r\n', 'output': ['xx\r\n']}, {'input': 'x x\r\n', 'output': ['x x\r\n']}, {'input': 'x,x\r\n', 'output': ['x, x\r\n']}, {'input': 'x.x\r\n', 'output': ['x. x\r\n']}, {'input': 'x!x\r\n', 'output': ['x! x\r\n']}, {'input': 'x?x\r\n', 'output': ['x? x\r\n']}, {'input': 'a!b\r\n', 'output': ['a! b\r\n']}, {'input': 'a, a\r\n', 'output': ['a, a\r\n']}, {'input': 'physicist  ?mathematician.astronomer\r\n', 'output': ['physicist? mathematician. astronomer\r\n']}, {'input': 'dfgdfg ? ddfgdsfg ? dsfgdsfgsdfgdsf   !   dsfg . sd dsg sdg !   sdfg\r\n', 'output': ['dfgdfg? ddfgdsfg? dsfgdsfgsdfgdsf! dsfg. sd dsg sdg! sdfg\r\n']}, {'input': 'jojo ! majo ,     hehehehe?  jo . kok\r\n', 'output': ['jojo! majo, hehehehe? jo. kok\r\n']}, {'input': 'adskfj,kjdf?kjadf kj!kajs f\r\n', 'output': ['adskfj, kjdf? kjadf kj! kajs f\r\n']}, {'input': 'a , b\r\n', 'output': ['a, b\r\n']}, {'input': 'ahmed? ahmed ? ahmed ?ahmed\r\n', 'output': ['ahmed? ahmed? ahmed? ahmed\r\n']}, {'input': 'kjdsf, kdjf?kjdf!kj kdjf\r\n', 'output': ['kjdsf, kdjf? kjdf! kj kdjf\r\n']}, {'input': 'italian physicist  .mathematician?astronomer\r\n', 'output': ['italian physicist. mathematician? astronomer\r\n']}, {'input': 'galileo galilei was an   italian physicist  ,  mathematician,astronomer\r\n', 'output': ['galileo galilei was an italian physicist, mathematician, astronomer\r\n']}, {'input': 'z zz zz z z! z z aksz zkjsdfz kajfz z !akj , zz a z\r\n', 'output': ['z zz zz z z! z z aksz zkjsdfz kajfz z! akj, zz a z\r\n']}, {'input': 'jojo ! maja . jaooo\r\n', 'output': ['jojo! maja. jaooo\r\n']}, {'input': 'a ! b\r\n', 'output': ['a! b\r\n']}, {'input': 'fff , fff\r\n', 'output': ['fff, fff\r\n']}, {'input': 'a!a?a ! a ? a\r\n', 'output': ['a! a? a! a? a\r\n']}, {'input': 'a!a\r\n', 'output': ['a! a\r\n']}, {'input': 'a!a a ! a ? a ! a , a . a\r\n', 'output': ['a! a a! a? a! a, a. a\r\n']}, {'input': 'casa?mesa, y unos    de   , los sapotes?l\r\n', 'output': ['casa? mesa, y unos de, los sapotes? l\r\n']}, {'input': 'ff ! ff\r\n', 'output': ['ff! ff\r\n']}, {'input': 'i love evgenia   ! x\r\n', 'output': ['i love evgenia! x\r\n']}, {'input': 'galileo galilei was an   italian physicist  ,mathematician,astronomer?asdf  ?asdfff?asdf. asdf.dfd  .dfdf   ?  df d! sdf dsfsa   sdf  !   asdf ? sdfsdf, dfg   a   ! b ?a\r\n', 'output': ['galileo galilei was an italian physicist, mathematician, astronomer? asdf? asdfff? asdf. asdf. dfd. dfdf? df d! sdf dsfsa sdf! asdf? sdfsdf, dfg a! b? a\r\n']}, {'input': 'a  ,  a\r\n', 'output': ['a, a\r\n']}, {'input': 'x,   werwr, werwerwr we,rwer ,wer\r\n', 'output': ['x, werwr, werwerwr we, rwer, wer\r\n']}, {'input': 'abcabc,    abcabc\r\n', 'output': ['abcabc, abcabc\r\n']}, {'input': 'i love evgenia x! x\r\n', 'output': ['i love evgenia x! x\r\n']}, {'input': 'gg    gg,h,h,j,i,jh   , jjj ,  jj ,aadd , jjj jjj\r\n', 'output': ['gg gg, h, h, j, i, jh, jjj, jj, aadd, jjj jjj\r\n']}, {'input': 'mt test   !  case\r\n', 'output': ['mt test! case\r\n']}, {'input': 'dolphi ! nigle\r\n', 'output': ['dolphi! nigle\r\n']}, {'input': 'asdasdasd.asdasdasdasd?asdasdasd!asdasdasd,asdasdasdasd\r\n', 'output': ['asdasdasd. asdasdasdasd? asdasdasd! asdasdasd, asdasdasdasd\r\n']}, {'input': 'x,   x,  ds  ,ertert,   ert, et  et\r\n', 'output': ['x, x, ds, ertert, ert, et et\r\n']}, {'input': 'anton!love ?yourself\r\n', 'output': ['anton! love? yourself\r\n']}, {'input': 'facepalm ? yes , lol ! yeah\r\n', 'output': ['facepalm? yes, lol! yeah\r\n']}, {'input': 'a ! a\r\n', 'output': ['a! a\r\n']}, {'input': 'adf!kadjf?kajdf,lkdas. kd ! akdjf\r\n', 'output': ['adf! kadjf? kajdf, lkdas. kd! akdjf\r\n']}, {'input': 'a?  x\r\n', 'output': ['a? x\r\n']}, {'input': 'read problem carefully ! heh\r\n', 'output': ['read problem carefully! heh\r\n']}, {'input': 'a?a?a?a.a\r\n', 'output': ['a? a? a? a. a\r\n']}, {'input': 'a. v\r\n', 'output': ['a. v\r\n']}, {'input': 'a!a a  !  a  ?  a ! a , a . a aaaaaa ! a ! a. a a .a a.a aa.aa aa . aa            aa .aa  aa. aa\r\n', 'output': ['a! a a! a? a! a, a. a aaaaaa! a! a. a a. a a. a aa. aa aa. aa aa. aa aa. aa\r\n']}, {'input': 'a,  a\r\n', 'output': ['a, a\r\n']}, {'input': 'a!a!a\r\n', 'output': ['a! a! a\r\n']}, {'input': 'a.a.a.a\r\n', 'output': ['a. a. a. a\r\n']}, {'input': 'a, b\r\n', 'output': ['a, b\r\n']}, {'input': 'galileo galilei was an italian physicist, mathematician, astronomer\r\n', 'output': ['galileo galilei was an italian physicist, mathematician, astronomer\r\n']}, {'input': 'a!a!a!a\r\n', 'output': ['a! a! a! a\r\n']}, {'input': 'af ! kadjf ? kjdfkj!kjadkfjz z z a a! ka,kjf\r\n', 'output': ['af! kadjf? kjdfkj! kjadkfjz z z a a! ka, kjf\r\n']}, {'input': 'ab cd,k\r\n', 'output': ['ab cd, k\r\n']}, {'input': 'a!n , to\r\n', 'output': ['a! n, to\r\n']}, {'input': 'dolphi    !    nigle\r\n', 'output': ['dolphi! nigle\r\n']}, {'input': 'u, sux\r\n', 'output': ['u, sux\r\n']}]


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Suptee
 */
public class Arrays_572A {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine());

            int nA = Integer.parseInt(st.nextToken());
            int nB = Integer.parseInt(st.nextToken());

            int[] arrayA = new int[nA];
            int[] arrayB = new int[nB];

            StringTokenizer st1 = new StringTokenizer(br.readLine());
            int k = Integer.parseInt(st1.nextToken());
            int m = Integer.parseInt(st1.nextToken());

            StringTokenizer st2 = new StringTokenizer(br.readLine());
            int i = 0;
            while (st2.hasMoreTokens() && i < nA) {
                arrayA[i] = Integer.parseInt(st2.nextToken());
                //System.out.println("arrayA : "+arrayA[i]);
                i++;
            }

            StringTokenizer st3 = new StringTokenizer(br.readLine());
            int j = 0;
            while (st3.hasMoreTokens() && j < nB) {
                arrayB[j] = Integer.parseInt(st3.nextToken());
               // System.out.println("arrayB : "+arrayB[j]);
                j++;
            }

            int count = 0;
            for (int indexA = 0; indexA < k; indexA++) {
                for(int indexB = nB - 1; indexB >= (nB - m); indexB --) {
                    if(arrayA[indexA] < arrayB[indexB]) {
                        count++;
                    }
                }
            }

            if(count == k) {
                System.out.println("YES");
            }
            else {
                System.out.println("NO");
            }

        } catch (IOException ex) {
            Logger.getLogger(Arrays_572A.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Suptee
 */
public class Arrays_572A {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine());

            int nA = Integer.parseInt(st.nextToken());
            int nB = Integer.parseInt(st.nextToken());

            StringTokenizer st1 = new StringTokenizer(br.readLine());
            int k = Integer.parseInt(st1.nextToken());
            int m = Integer.parseInt(st1.nextToken());

            int[] arrayA = new int[k];
            int[] arrayB = new int[nB];
            StringTokenizer st2 = new StringTokenizer(br.readLine());
            int i = 0;
            while (st2.hasMoreTokens() && i < k) {
                arrayA[i] = Integer.parseInt(st2.nextToken());
                //System.out.println("arrayA : "+arrayA[i]);
                i++;
            }

            StringTokenizer st3 = new StringTokenizer(br.readLine());
            int j = 0;
            while (st3.hasMoreTokens() && j < nB) {
                arrayB[j] = Integer.parseInt(st3.nextToken());
                //System.out.println("arrayB : "+arrayB[j]);
                j++;
            }

            boolean found = true;
           // for (int indexA = 0; indexA < k; indexA++) {
                for(int indexB = nB - 1; indexB >= (nB - m); indexB --) {
                    if(!(arrayA[k-1] < arrayB[indexB])) {
                        found = false;
                    }
                }
            //}

            if(found) {
                System.out.println("YES");
            }
            else {
                System.out.println("NO");
            }

        } catch (IOException ex) {
            Logger.getLogger(Arrays_572A.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}


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

public class SecOrderStatics {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n =scan.nextInt();
		int[] a= new int[n];
		HashSet h= new HashSet();
		for(int i=0;i<n;i++)
		{
			a[i]=scan.nextInt();
		}
		Arrays.sort(a);
		ArrayList al=new ArrayList();
		for(int i=0;i<n;i++)
		{
			if(h.contains(a[i]))
			{
				continue;
			}
			al.add(a[i]);
			h.add(a[i]);
		}
		if(n>2)
		{
			System.out.println(al.get(1));
		}
		else System.out.println("NO");
	}

}

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

}


import java.util.Scanner;

public class main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         Scanner in = new Scanner(System.in);
         long l=in.nextLong();
         long r=in.nextLong();
         String s=Long.toString(r);

         long x;
         if(r<10)x=r;
         else
         {boolean flag=false;
         while(s.charAt(0)!=s.charAt(s.length()-1))
          {   s=Long.toString(r);
              r--;
              s=Long.toString(r);
              flag=true;
          }
         if(flag)
           x=r/10+9;
         else x=r/10+10;
         }
         long y=0;
         if(l<10)y=l-1;
         else
         {   s=Long.toString(l);

             while(s.charAt(0)!=s.charAt(s.length()-1))
             {
                 l--;
                 s=Long.toString(l);

             }

                   y=l/10+9;

         }
        System.out.println(x-y);
    }

}

The Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r.

The single line contains a pair of integers l and r (1 ≤ l ≤ r ≤ 1018) — the boundaries of the interval. 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.

On a single line print a single integer — the answer to the problem.

NoteIn the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.

//package codeforces;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class A implements Closeable {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    A() throws IOException {
//        reader = new BufferedReader(new FileReader("input.txt"));
//        writer = new PrintWriter(new FileWriter("output.txt"));
    }

    StringTokenizer stringTokenizer;

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

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

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

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

    private int MOD = 1000 * 1000 * 1000 + 7;

    int sum(int a, int b) {
        a += b;
        return a >= MOD ? a - MOD : a;
    }

    int product(int a, int b) {
        return (int) (1l * a * b % MOD);
    }

    int pow(int x, int k) {
        int result = 1;
        while (k > 0) {
            if (k % 2 == 1) {
                result = product(result, x);
            }
            x = product(x, x);
            k /= 2;
        }
        return result;
    }

    int inv(int x) {
        return pow(x, MOD - 2);
    }

    void solve() throws IOException {
        class Utils {
            boolean isGood(long x) {
                List<Integer> d = new ArrayList<>();
                for(long y = x; y > 0; y /= 10) {
                    d.add((int)(y % 10));
                }
                return d.get(0) == (int)d.get(d.size() - 1);
            }

            long brute(long ceiling) {
                long answer = 0;
                for(int i = 1; i <= ceiling; i++) {
                    if(isGood(i)) {
                        answer++;
                    }
                }
                return answer;
            }

            long count(long ceiling) {
                if(ceiling <= 1000) {
                    return brute(ceiling);
                }
                long p = 10;
                long answer = 0;
                while(ceiling >= p && p < 1000000l * 1000000 * 1000000) {
                    answer += 9 * Math.max(1, p / 100);
                    p *= 10;
                }
                p /= 10;
                long firstDigit = ceiling / p;
                for(int i = 1; i < firstDigit; i++) {
                    answer += p / 10;
                }
                long x = ceiling % p;
                if(x == 0) {
                    return answer;
                }
                answer += Math.max(0, x / 10);
                long y = firstDigit * p + x / 10 * 10;
                while(y <= ceiling) {
                    if(y % 10 == firstDigit) {
                        answer++;
                    }
                    y++;
                }
                return answer;
            }
        }
        Utils utils = new Utils();
//        for(int i = 1; i <= 1000000; i++) {
//            if(i % 1000 == 0) {
//                System.out.println("i = " + i);
//            }
//            if(utils.count(i) != utils.brute(i)) {
//                writer.println("failed " + i);
//                return;
//            }
//        }
        long l = nextLong();
        long r = nextLong();
        writer.println(utils.count(r) - utils.count(l - 1));
    }

    public static void main(String[] args) throws IOException {
        try (A a = new A()) {
            a.solve();
        }
    }

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


import org.w3c.dom.ls.LSOutput;

import java.lang.reflect.Array;
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]);
            else {
                sum-=a[i];
            }
        }

        System.out.println(sum);

    }
}

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

    }
}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author johnny16
 *
 */
public class PocketBook {
	static int mod = 1000000007;

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

	public static void main(String[] args) throws IOException {
		Reader in = new Reader();
		int i, j, t, n, m;
		// t = in.nextInt();
		long ans;
		n = in.nextInt();
		m = in.nextInt();
		in.readLine();
		String s;
		boolean unq[][] = new boolean[m][26];
		ans = 1;
		for (i = 0; i < n; i++) {
			s = in.readLine();
			for (j = 0; j < m; j++) {
				int c = (int) s.charAt(j) - 65;
				unq[j][c] = true;
			}
		}
		for (i = 0; i < m; i++) {
			int x = 0;
			for (j = 0; j < 26; j++) {
				if (unq[i][j])
					x++;
			}
			ans = ((ans % mod) * x) % mod;
		}
		System.out.println(ans);
	}
}

One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

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

public class C
{

	public static void main(String[] args)throws IOException
	{
		BufferedReader ob = new BufferedReader(new InputStreamReader(System.in));
		StringBuffer sb = new StringBuffer();

		String s[]=ob.readLine().split(" ");
		int n=Integer.parseInt(s[0]);
		long mod = 1000000007L;
		int m=Integer.parseInt(s[1]);
		long ans = 1;
		HashSet<Character> set[] = new HashSet[m];
		for(int i = 0;i < m;i++)
			set[i] = new HashSet<>();
		for(int i = 0;i < n;i++)
		{
			String str=ob.readLine();
			for(int j = 0;j < m;j++)
				set[j].add(str.charAt(j));
		}
		for(int i = 0;i < m;i++)
		{
//			System.out.println("size = "+set[i].size());
			ans*=set[i].size();
			ans%=mod;
		}
		System.out.println(ans);

	}

}

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nXKNWGHQHIOXUPF\r\nDDNRUKVUGHWMXW\r\nMTIZFNAAFEAPHX\r\nIXBQOOHEULZYHU\r\nMRCSREUEOOMUUN\r\nHJTSQWKUFYZDQU\r\nGMCMUZCOPRVEIQ\r\nXBKKGGJECOBLTH\r\nXXHTLXCNJZJUAF\r\nVLJRKXXXWMTPKZ\r\nPTYMNPTBBCWKAD\r\nQYJGOBUBHMEDYE\r\nGTKUUVVNKAHTUI\r\nZNKXYZPCYLBZFP\r\nQCBLJTRMBDWNNE\r\nTDOKJOBKEOVNLZ\r\nFKZUITYAFJOQIM\r\nUWQNSGLXEEIRWF\r\n', 'output': ['515139391\r\n']}, {'input': '5 14\r\nAQRXUQQNSKZPGC\r\nDTTKSPFGGVCLPT\r\nVLZQWWESCHDTAZ\r\nCOKOWDWDRUOMHP\r\nXDTRBIZTTCIDGS\r\n', 'output': ['124999979\r\n']}, {'input': '9 23\r\nOILBYKHRGMPENVFNHLSIUOW\r\nLPJFHTUQUINAALRDGLSQUXR\r\nLYYJJEBNZATAFQWTDZSPUNZ\r\nHSJPIQKKWWERJZIEMLCZUKI\r\nOJYIEYDGPFWRHCMISJCCUEM\r\nLMGKZVFYIVDRTIHBWPCNUTG\r\nUBGGNCITVHAIPKXCLTSAULQ\r\nOWSAWUOXQDBSXXBHTLSXUVD\r\nUGQTIZQPBGMASRQPVPSFUWK\r\n', 'output': ['454717784\r\n']}, {'input': '25 4\r\nLVKG\r\nMICU\r\nZHKW\r\nLFGG\r\nOWQO\r\nLCQG\r\nLVXU\r\nOUKB\r\nLNQX\r\nZJTO\r\nOOQX\r\nLVQP\r\nMFQB\r\nMRQV\r\nOIQH\r\nOPXX\r\nXFKU\r\nFCQB\r\nZPKH\r\nLVCH\r\nNFCU\r\nOVQW\r\nOZKU\r\nLFHX\r\nLPXO\r\n', 'output': ['5733\r\n']}, {'input': '30 10\r\nUTNTGOKZYJ\r\nQHOUHNYZVW\r\nLTVGHJRZVW\r\nMZHYHOLZYJ\r\nERYEUEPZYE\r\nUZDBFTURYJ\r\nRVSMQTIZGW\r\nWDJQHMIRYY\r\nKCORHQPZYE\r\nRRPLFOZZVY\r\nJTXMFNNNYJ\r\nMVTGGOZZVV\r\nEHAFFNUZVF\r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\n', 'output': ['1048576\r\n']}, {'input': '1 20\r\nAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '20 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\n', 'output': ['7\r\n']}, {'input': '5 60\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\r\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\r\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\r\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\r\n', 'output': ['449874206\r\n']}, {'input': '50 4\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\n', 'output': ['10000\r\n']}, {'input': '1 100\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\n', 'output': ['2\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\n', 'output': ['14\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\n', 'output': ['26\r\n']}]


import java.util.*;

public class Main
{
	static int total[][],n,m;

	public static void main(String[] args)
	{

		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		m = in.nextInt();

		total = new int[n][m];
		int maxInt = 200;

		for (int i=0;i < n;i++)
			for (int j=0;j < m;j++)
				total[i][j] = maxInt;

		String str;
		int half = m % 2 == 0 ? m / 2 + 1 : m / 2;
		int count =0;

		for (int i=0;i < n;i++)
		{
			str = in.next();

			for (int j=0;j < m;j++)
				if (str.charAt(j) == '1')
				{
					total[i][j] = 0;
					fillLeft(i, j, half);
					fillRight(i, j, half);
				}
				else
					count++;

			if (count == m)
			{
				System.out.println(-1);
				return;
			}

		}//read data

		int min = maxInt,v;

		for (int i =0;i < m;i++)
		{
			if ((v = sumColumn(i)) < min)
				min = v;

			if(v==0)
			{
				System.out.println(-1);
				return;
			}
		}

		System.out.println(min);

	}

	public static int sumColumn(int col)
	{
		int sum = 0;

		for (int i=0;i < n;i++)
			sum += total[i][col];

		return sum;
	}

	public static void fillLeft(int row, int st, int step)
	{

		for (int i =1;i <= step;i++)
		{
			st = st == 0 ? m - 1 : --st;
			total[row][st] = Math.min(total[row][st], i);
		}

	}

	public static void fillRight(int row, int st, int step)
	{

		for (int i =1;i <= step;i++)
		{
			st = st == m - 1 ? 0 : ++st;
			total[row][st] = Math.min(total[row][st], i);
		}

	}

}

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


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

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


/* package whatever; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
public class Leader
{
    public static void main(String[] args) throws java.lang.Exception {
		Scanner f = new Scanner(System.in);
		int n=f.nextInt();
		String[] matrix = new String[n];
		int max=0;
		int index=0;

		for(int i=0; i<n; i++){
		String handle = f.next();
		int score =(100*f.nextInt() -50*f.nextInt() + f.nextInt()+f.nextInt()+f.nextInt()+f.nextInt()+f.nextInt());
			matrix[i]= handle+" "+ score;
		if(score>max){
			max=score;
			index=i;
		}
		}

		System.out.println(matrix[index].substring(0,matrix[index].indexOf(' ')));

	}

}

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


import java.util.Scanner;

public class Diversity {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String str = s.next();
        int k = s.nextInt();
        int different = 0;
        int[] a = new int[26];
        for(int i = 0; i < str.length(); i++) {
            a[str.charAt(i) - 97]++;
        }
        for(int i = 0; i < a.length; i++) {
            if(a[i] != 0) different++;
        }
        if(str.length() - different >= k - different) System.out.println(str.length() - different);
        else System.out.println("impossible");
    }
}

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

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

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

        String str = scan.next();
        int n = str.length();
        int k = scan.nextInt();
        if(k == 1)
        	System.out.println(0);
        else{
	        HashSet<Character> set = new HashSet<Character>();
		    for(int i = 0; i < n; i++)
		    	set.add(str.charAt(i));
		    int res = (k-set.size());
		    if(k > n)
		    	System.out.println("impossible");
		    else if(res >= 0)
		    	System.out.println(res);
		    else
		    	System.out.println(0);
	  	}
		scan.close();
	}
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        int n = sc.nextInt();
        boolean[] exist = new boolean[n];
        for (int i = 0; i < n; i++) {
            exist[sc.nextInt()-1] = true;
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += exist[i] ? 0 : 1;
        }
        System.out.println(res);
    }
}

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

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

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

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

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

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

        public FastScanner()
        {
            stream = System.in;
        }

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

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

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

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

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

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

        String next(){
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do{
                res.appendCodePoint(c);
                c = read();
            }while(!isSpaceChar(c));
            return res.toString();
        }

        String nextLine(){
            int c = read();
            while (isEndline(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do{
                res.appendCodePoint(c);
                c = read();
            }while(!isEndline(c));
            return res.toString();
        }
    }

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        byte vis[] =new byte[5005];
            int n = in.nextInt();

            int ans = 0;
            int t;
            for(int i=0;i<n;i++)
            {
                t= in.nextInt();
                if(t > n || vis[t]!=0)
                    ans++;
                else
                    vis[t] = 1;
            }
          System.out.println(ans);

    }

}