As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

// practice with kaiboy
import java.io.*;
import java.util.*;

public class CF157D extends PrintWriter {
	CF157D() { super(System.out); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF157D o = new CF157D(); o.main(); o.flush();
	}

	void main() {
		int n = sc.nextInt();
		int m = sc.nextInt();
		int[] aa = new int[n];
		int[] pp = new int[n + 1];
		int[] qq = new int[n + 1];
		int q = 0;
		for (int i = 0; i < n; i++) {
			int a = sc.nextInt();
			aa[i] = a;
			if (a > 0)
				pp[a]++;
			else {
				qq[-a]++;
				q++;
			}
		}
		boolean[] yes = new boolean[n + 1];
		int k = 0;
		for (int a = 1; a <= n; a++)
			if (pp[a] + q - qq[a] == m) {
				yes[a] = true;
				k++;
			}
		for (int i = 0; i < n; i++) {
			int a = aa[i];
			if (a > 0)
				println(yes[a] ? (k == 1 ? "Truth" : "Not defined") : "Lie");
			else
				println(yes[-a] ? (k == 1 ? "Lie" : "Not defined") : "Truth");
		}
	}
}

[{'input': '1 1\r\n+1\r\n', 'output': ['Truth\r\n']}, {'input': '3 2\r\n-1\r\n-2\r\n-3\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '4 1\r\n+2\r\n-3\r\n+4\r\n-1\r\n', 'output': ['Lie\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': '1 0\r\n-1\r\n', 'output': ['Lie\r\n']}, {'input': '2 2\r\n+1\r\n+1\r\n', 'output': ['Truth\r\nTruth\r\n']}, {'input': '2 1\r\n+2\r\n+1\r\n', 'output': ['Not defined\r\nNot defined\r\n']}, {'input': '2 0\r\n-2\r\n-2\r\n', 'output': ['Lie\r\nLie\r\n']}, {'input': '3 1\r\n+2\r\n+3\r\n+3\r\n', 'output': ['Truth\r\nLie\r\nLie\r\n']}, {'input': '6 3\r\n+5\r\n+5\r\n+5\r\n+1\r\n+1\r\n+1\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '4 3\r\n-4\r\n-3\r\n-1\r\n-3\r\n', 'output': ['Not defined\r\nTruth\r\nNot defined\r\nTruth\r\n']}, {'input': '10 4\r\n-8\r\n+1\r\n-6\r\n-10\r\n+5\r\n-6\r\n-8\r\n-8\r\n-4\r\n-8\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-4\r\n+4\r\n+4\r\n-9\r\n-9\r\n-4\r\n-4\r\n+2\r\n-9\r\n-4\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '7 2\r\n+5\r\n+5\r\n+5\r\n-2\r\n+1\r\n-5\r\n-6\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nTruth\r\nNot defined\r\n']}, {'input': '7 4\r\n+7\r\n-3\r\n-3\r\n-4\r\n+3\r\n+3\r\n+3\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '6 3\r\n-6\r\n-1\r\n+5\r\n+1\r\n+6\r\n+1\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': '5 3\r\n-2\r\n+2\r\n+2\r\n-3\r\n+5\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\n']}, {'input': '3 0\r\n-2\r\n-2\r\n-2\r\n', 'output': ['Lie\r\nLie\r\nLie\r\n']}, {'input': '5 3\r\n-1\r\n-1\r\n-4\r\n+1\r\n-4\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': '9 6\r\n+2\r\n+7\r\n+7\r\n-1\r\n-4\r\n+7\r\n-7\r\n+7\r\n+5\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '43 18\r\n-14\r\n-28\r\n+16\r\n+10\r\n+25\r\n-30\r\n+25\r\n+30\r\n+25\r\n+25\r\n+25\r\n+25\r\n-25\r\n+22\r\n+3\r\n-17\r\n+16\r\n-25\r\n+10\r\n+14\r\n+41\r\n+25\r\n-25\r\n+33\r\n+24\r\n-23\r\n-25\r\n+25\r\n-22\r\n+29\r\n+28\r\n-25\r\n-25\r\n-29\r\n+11\r\n+26\r\n-25\r\n+25\r\n+10\r\n+1\r\n-20\r\n-17\r\n+23\r\n', 'output': ['Truth\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '28 12\r\n+10\r\n-7\r\n+17\r\n-20\r\n+7\r\n-7\r\n+13\r\n-21\r\n-7\r\n-7\r\n-18\r\n+7\r\n+7\r\n+3\r\n+6\r\n+14\r\n+7\r\n-24\r\n-21\r\n-7\r\n-7\r\n+4\r\n+7\r\n-7\r\n+21\r\n-7\r\n-26\r\n+7\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '17 9\r\n-6\r\n+16\r\n+5\r\n+16\r\n-17\r\n+17\r\n-11\r\n+5\r\n+14\r\n+5\r\n-8\r\n-5\r\n+6\r\n-2\r\n-11\r\n+4\r\n+17\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': '14 3\r\n+14\r\n+12\r\n-9\r\n+9\r\n-9\r\n-9\r\n+8\r\n+9\r\n+2\r\n+1\r\n-13\r\n-9\r\n+13\r\n+3\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': '10 4\r\n-9\r\n-8\r\n-5\r\n-9\r\n-7\r\n-9\r\n-9\r\n-9\r\n-4\r\n-9\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-10\r\n-10\r\n-10\r\n-5\r\n-1\r\n+10\r\n-3\r\n-10\r\n-9\r\n-10\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 4\r\n-3\r\n-3\r\n-3\r\n-3\r\n-3\r\n-2\r\n-2\r\n-6\r\n-7\r\n-3\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 6\r\n-9\r\n-7\r\n-5\r\n-5\r\n-4\r\n-2\r\n-8\r\n-5\r\n-5\r\n-9\r\n', 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 4\r\n-8\r\n-2\r\n-8\r\n+1\r\n-4\r\n-8\r\n-2\r\n-8\r\n-8\r\n-1\r\n', 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 2\r\n-8\r\n+10\r\n+1\r\n+8\r\n+4\r\n+8\r\n+6\r\n-8\r\n+10\r\n+1\r\n', 'output': ['Not defined\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nLie\r\n']}, {'input': '10 3\r\n+9\r\n+3\r\n+8\r\n+3\r\n+6\r\n-3\r\n+6\r\n+8\r\n+3\r\n+7\r\n', 'output': ['Lie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\n']}, {'input': '10 8\r\n-2\r\n+9\r\n+9\r\n-4\r\n+9\r\n+9\r\n+4\r\n-9\r\n-3\r\n+9\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '10 7\r\n-4\r\n+6\r\n+4\r\n+9\r\n+6\r\n+6\r\n+6\r\n+6\r\n+6\r\n+2\r\n', 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 4\r\n+3\r\n+5\r\n+6\r\n+10\r\n+5\r\n+5\r\n+6\r\n+8\r\n+5\r\n+6\r\n', 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 7\r\n-6\r\n-10\r\n-3\r\n-1\r\n-3\r\n-7\r\n-2\r\n-7\r\n-7\r\n-3\r\n', 'output': ['Truth\r\nTruth\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '10 5\r\n-4\r\n-4\r\n-1\r\n-5\r\n-7\r\n-4\r\n-4\r\n-4\r\n-1\r\n-7\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '10 5\r\n-9\r\n-7\r\n-6\r\n-3\r\n-10\r\n-10\r\n-10\r\n-10\r\n-10\r\n-2\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 3\r\n-10\r\n-10\r\n-10\r\n-3\r\n-10\r\n-10\r\n-10\r\n-8\r\n-4\r\n-10\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-8\r\n-8\r\n-4\r\n-9\r\n-10\r\n-2\r\n-9\r\n-8\r\n-8\r\n-8\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': '10 5\r\n+7\r\n+8\r\n+9\r\n+1\r\n+7\r\n+7\r\n+7\r\n+6\r\n+6\r\n+7\r\n', 'output': ['Truth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 5\r\n+2\r\n+2\r\n+2\r\n+2\r\n+9\r\n+10\r\n+8\r\n+7\r\n+4\r\n+2\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 9\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+5\r\n+7\r\n+7\r\n+7\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': '10 3\r\n+10\r\n+2\r\n+10\r\n+9\r\n+1\r\n+9\r\n+4\r\n+9\r\n+3\r\n+2\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': '10 6\r\n+10\r\n+10\r\n+10\r\n+3\r\n+10\r\n+10\r\n+6\r\n+6\r\n+10\r\n+8\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '3 2\r\n-1\r\n+2\r\n+3\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\n']}]


It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an n - 1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than m times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only k minutes left before morning, and on each of these k minutes he can perform no more than m operations. All that remains in Joe's pocket, is considered his loot.Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.

The first line contains integers n, m and k (1 ≤ n ≤ 104, 1 ≤ m, k ≤ 109). The next line contains n numbers. The i-th number is equal to the amount of diamonds in the i-th cell — it is an integer from 0 to 105.

Print a single number — the maximum number of diamonds Joe can steal.

NoteIn the second sample Joe can act like this:The diamonds' initial positions are 4 1 3.During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket.By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off.During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket.By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off.Now Joe leaves with 2 diamonds in his pocket.

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

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int k = sc.nextInt();
        int[] a = sc.nextIntArray(n);
        if (n % 2 == 0) {
            System.out.println(0);
            return;
        }
        int min = (int) (1e5 + 10);
        for (int i = 0; i < n; i += 2)
            min = Math.min(min, a[i]);
        int y = n / 2 + 1;
        out.println(Math.min(min, 1l * k * (m / y)));
        out.flush();
        out.close();
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

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

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

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

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

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

        public char nextChar() throws IOException {
            return next().charAt(0);
        }

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

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

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

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

        public Integer[] nextIntegerArray(int n) throws IOException {
            Integer[] a = new Integer[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public double[] nextDoubleArray(int n) throws IOException {
            double[] ans = new double[n];
            for (int i = 0; i < n; i++)
                ans[i] = nextDouble();
            return ans;
        }

        public short nextShort() throws IOException {
            return Short.parseShort(next());
        }

    }

}


Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.

The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.

Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.

NoteThe images below illustrate statement tests.The first test:In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.The second test:In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.

import java.util.Scanner;

public class frames {
public static void main(String args[]){
	Scanner s = new Scanner(System.in);
	int n = s.nextInt(),m=s.nextInt(),a=s.nextInt(),b=s.nextInt();
	if(a<=m&&b<=m){
		System.out.println(1);
	}
	else if(m==1||a==b){
		System.out.println(1);
	}
	else if(b-a<m&&(b/m-1==a/m)&&b%m==0){

	System.out.println(1);
	}
	else if(b-a<m&&(b/m==a/m)&&a%m!=0){

		System.out.println(1);
	}
	else if(a%m==1&&n==b){
		System.out.println(1);
	}
	else if (a%m==1&&b%m==0){
		System.out.println(1);
	}
	else if (a%m!=1&&b%m==0){
		System.out.println(2);
	}
	else if (a%m==1&&b%m!=0){
		System.out.println(2);
	}
	else if (a%m!=1&&b==n||(a%m==0&&(b%m==m-1))){

		System.out.println(2);
	}
	else if (a%m-b%m==1){
		System.out.println(2);
	}
	else if(a%m==0&&b%m!=0&&a/m==b/m){

		System.out.println(2);
	}
	else if(a%m!=0&&b%m!=0&&a/m==b/m-1){
		System.out.println(2);

	}

	else
		System.out.println(3);

}
}


Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 ≤ x, y ≤ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 ≤ ti, ci ≤ 109), which describe the taxi driver that waits at the i-th junction — the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character.

If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteAn optimal way — ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.

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

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

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

    static class seg_tree {
        long seg_tree[],seg_indx[];
        public seg_tree(int n,long arr[]) {
            seg_tree=new long[4*n];
            seg_indx=new long[4*n];
            create_seg_tree(arr,0,0,n-1);
        }

        //0 index-Left child-(2*i+1) Right Child-(2*i+2)

        public void create_seg_tree(long arr[],int vertex,int l,int r) {
            if(l==r) {
                seg_indx[vertex]=r;
                seg_tree[vertex]=arr[r];
                return;
            }
            int mid=(l+r)/2;
            //Left Child
            create_seg_tree(arr,(2*vertex)+1,l,mid);
            //Right Child
            create_seg_tree(arr,(2*vertex)+2,mid+1,r);
            //Filling this node
            if(seg_tree[(2*vertex)+1]<seg_tree[(2*vertex)+2]) {
                seg_tree[vertex]=seg_tree[(2*vertex)+1];
                seg_indx[vertex]=seg_indx[(2*vertex)+1];
            }
            else {
                seg_tree[vertex]=seg_tree[(2*vertex)+2];
                seg_indx[vertex]=seg_indx[(2*vertex)+2];
            }
        }

        public long[] min(int vertex,int l,int r,int ql,int qr) {  //ql->query left , qr-> query right l->curr Segmrnt left    r->curr segment right
            if(ql>qr) {
                return new long[]{Long.MAX_VALUE,-1};
            }

            if(ql==l && qr==r) {
                return new long[]{seg_tree[vertex],seg_indx[vertex]};
            }
            int mid=(l+r)/2;

            //Left Child
            long min1[]=min((2*vertex)+1,l,mid,ql,Math.min(qr, mid));

            //Right Child
            long min2[]=min((2*vertex)+2,mid+1,r,Math.max(mid+1,ql),qr);

            if(min1[0]<min2[0]) {
                return min1;
            }
            else {
                return min2;
            }
        }

        public void update(int vertex,int l,int r,int pos,long value) {   //pos->Position of the update   value->updates value
            if(l==r) {
                seg_tree[vertex]=value;
                return;
            }
            int mid=(l+r)/2;
            //Left Child
            if(pos<=mid) {
                update((2*vertex)+1,l,mid,pos,value);
            }
            //Right Child
            else {
                update((2*vertex)+2,mid+1,r,pos,value);
            }
            if(seg_tree[(2*vertex)+1]<seg_tree[(2*vertex)+2]) {
                seg_tree[vertex]=seg_tree[(2*vertex)+1];
                seg_indx[vertex]=seg_indx[(2*vertex)+1];
            }
            else {
                seg_tree[vertex]=seg_tree[(2*vertex)+2];
                seg_indx[vertex]=seg_indx[(2*vertex)+2];
            }
        }
    }

    static ArrayList<Integer> adj_lst[],weight[];
    static long len[],cost[];
    static boolean vis[];
    static long dist[][],dp[][];
    static int n,x,y;
    static seg_tree s_tree;
    public static void main(String args[]) throws IOException {
        Scan input=new Scan();
        n=input.scanInt();
        int m=input.scanInt();
        x=input.scanInt()-1;
        y=input.scanInt()-1;
        len=new long[n];
        cost=new long[n];
        adj_lst=new ArrayList[n];
        weight=new ArrayList[n];
        vis=new boolean[n];
        dist=new long[n][n];
        for(int i=0;i<n;i++) {
            adj_lst[i]=new ArrayList<>();
            weight[i]=new ArrayList<>();
        }
        for(int i=0;i<m;i++) {
            int u=input.scanInt()-1;
            int v=input.scanInt()-1;
            int wei=input.scanInt();
            adj_lst[u].add(v);
            adj_lst[v].add(u);
            weight[u].add(wei);
            weight[v].add(wei);
        }
        for(int i=0;i<n;i++) {
            len[i]=input.scanInt();
            cost[i]=input.scanInt();
        }
        for(int i=0;i<n;i++) {
            Arrays.fill(dist[i], Long.MAX_VALUE);
            dist[i][i]=0;
            s_tree=new seg_tree(n,dist[i]);
            vis=new boolean[n];
            Dijkstras(i,i);
        }
        vis=new boolean[n];
        System.out.println(solve());
    }
    public static long solve() {
        long fin[]=new long[n];
        int root=x;
        Arrays.fill(fin, Long.MAX_VALUE);
        fin[x]=0;
        while(true) {
            vis[root]=true;
            for(int i=0;i<n;i++) {
                if(dist[root][i]>len[root]) {
                    continue;
                }
                fin[i]=Math.min(fin[i],fin[root]+cost[root]);
            }
            Long min=Long.MAX_VALUE;
            int indx=-1;
            for(int i=0;i<n;i++) {
                if(vis[i]) {
                    continue;
                }
                if(fin[i]<min) {
                    min=fin[i];
                    indx=i;
                }
            }
            if(indx==-1) {
                break;
            }
            root=indx;
        }
        if(fin[y]==Long.MAX_VALUE) {
            return -1;
        }
        return fin[y];
    }
    public static void Dijkstras(int source,int root) {
        vis[root]=true;
        dist[source][root]=0;
        while(true) {
//            System.out.println(root);
            vis[root]=true;
            for(int i=0;i<adj_lst[root].size();i++) {
                if(vis[adj_lst[root].get(i)]) {
                    continue;
                }
                if(dist[source][root]+weight[root].get(i)<dist[source][adj_lst[root].get(i)]) {
                    dist[source][adj_lst[root].get(i)]=dist[source][root]+weight[root].get(i);
                    s_tree.update(0, 0, n-1, adj_lst[root].get(i), dist[source][adj_lst[root].get(i)]);
                }
            }
            s_tree.update(0, 0, n-1, root, Long.MAX_VALUE);
            long tmp[]=s_tree.min(0, 0, n-1, 0, n-1);
            if(tmp[0]==Long.MAX_VALUE) {
                break;
            }
            root=(int)tmp[1];
        }
    }
}


In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.Traditionally GUC has n professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to n, with 1 being the most senior professor and n being the most junior professor.The ceremonial hall has n seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, m pairs of seats are in "senior-junior" relation, and the tradition requires that for all m pairs of seats (ai, bi) the professor seated in "senior" position ai should be more senior than the professor seated in "junior" position bi.GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that:   The seating of the professors changes every year.  Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall.  Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of n integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.Given n, the number of professors, y, the current year and m pairs of restrictions, output the arrangement of the professors for this year.

The first line contains three integers n, y and m (1 ≤ n ≤ 16, 2001 ≤ y ≤ 1018, 0 ≤ m ≤ 100) — the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively. The next m lines contain one pair of integers each, "ai bi", indicating that professor on the ai-th seat is more senior than professor on the bi-th seat (1 ≤ ai, bi ≤ n, ai ≠ bi). Some pair may be listed more than once. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin stream (you may also use the %I64d specificator).

Print the order in which the professors should be seated in the requested year. If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes).

NoteIn the first example the lexicographically first order of seating is 1 2 3.In the third example the GUC will run out of arrangements after the year 3630800.In the fourth example there are no valid arrangements for the seating.The lexicographical comparison of arrangements is performed by the < operator in modern programming languages. The arrangement a is lexicographically less that the arrangement b, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

1 2 3
1 2 3 7 4 6 5
The times have changed
The times have changed

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

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

    static class TaskC {
        long[][] dp;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            long y = in.nextLong() - 2000;
            int m = in.nextInt();

            final String noSolution = "The times have changed";

            boolean[][] graph = new boolean[n][n];
            for (int i = 0; i < m; ++i) {
                int x = in.nextInt() - 1, t = in.nextInt() - 1;
                graph[x][t] = true;
            }

            boolean[][] accesible = new boolean[n][n];
            for (int i = 0; i < n; ++i) {
                dfs(graph, accesible[i], i);
            }

            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (i != j && accesible[i][j] && accesible[j][i]) {
                        out.println(noSolution);
                        return;
                    }
                }
            }

            int[] g = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (accesible[i][j])
                        g[i] |= 1 << j;
                }
            }

            dp = new long[n + 1][1 << n];
            int[] pos = new int[n];
            Arrays.fill(pos, -1);

            if (count(pos, g) < y) {
                out.println(noSolution);
                return;
            }

            int[] fans = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (pos[j] != -1) continue;

                    pos[j] = i;
                    long x = count(pos, g);
                    if (x < y) {
                        y -= x;
                    } else {
                        fans[i] = j;
                        break;
                    }
                    pos[j] = -1;
                }
            }

            for (int i = 0; i < n; ++i)
                out.print((fans[i] + 1) + " ");
            out.println();
        }

        private void dfs(boolean[][] graph, boolean[] accesible, int node) {
            accesible[node] = true;
            for (int i = 0; i < graph.length; ++i) {
                if (graph[node][i] && !accesible[i]) {
                    dfs(graph, accesible, i);
                }
            }
        }

        private long count(int[] pos, int[] g) {
            int n = pos.length;
            int used = 0;
            for (int i = 0; i < n; ++i) {
                if (pos[i] != -1)
                    used |= 1 << pos[i];
            }
            for (long[] p : dp) {
                Arrays.fill(p, 0);
            }
            dp[0][0] = 1;
            for (int i = 0; i < n; ++i) {
                for (int conf = 0; conf < 1 << n; ++conf) {
                    if (dp[i][conf] == 0) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((conf & g[j]) != 0) continue;
                        if ((pos[i] == -1 && (used & (1 << j)) == 0) ||
                                pos[i] == j) {
                            dp[i + 1][conf | (1 << j)] += dp[i][conf];
                        }
                    }
                }
            }
            return dp[n][(1 << n) - 1];
        }

    }

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

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

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

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

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

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

            return res.toString();
        }

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

    }
}


In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representing a number that does not exceed b. Here a and b are some given constants, s1 and s2 are chosen by the players. The strings are allowed to contain leading zeroes.If a number obtained by the concatenation (joining together) of strings s1 and s2 is divisible by mod, then the second player wins. Otherwise the first player wins. You are given numbers a, b, mod. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.

The first line contains three integers a, b, mod (0 ≤ a, b ≤ 109, 1 ≤ mod ≤ 107).

If the first player wins, print "1" and the lexicographically minimum string s1 he has to write to win. If the second player wins, print the single number "2".

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String x is lexicographically less than string y if exists such i (1 ≤ i ≤ 9), that xi < yi, and for any j (1 ≤ j < i) xj = yj. These strings always have length 9.

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Game {
  public static void main(String[] args) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    String[] input = bf.readLine().split(" ");
    String answer = "";
    long a, b, mod, ans;
    boolean oneWin = false;
    a = Integer.parseInt(input[0]);
    b = Integer.parseInt(input[1]);
    mod = Integer.parseInt(input[2]);
    long limit = Math.min(a, mod);
    long res = 0;

    for (ans = 1; ans <= limit; ans++) {
      res = (((ans % mod) * (1000000000 % mod)) % mod);
      if ((mod - res)% mod > b) {
          oneWin = true;
          break;
      }
    }

    if (oneWin) {
      String temp = String.valueOf(ans);
      int digits = temp.length();
      for (int i = 0;i < 9 - digits; i++) {
        answer += "0";
      }
      answer += String.valueOf(ans);
      System.out.println("1 " + answer);
    } else {
      System.out.println(2);
    }
  }
}


You are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≤ l ≤ r ≤ |s|, correspond to a substring of the string s, starting in the position l and ending in the position r (inclusive).Let's define the function of two strings F(x, y) like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string x are equal to string y. Let's sort this list of pairs according to the pair's first number's increasing. The value of function F(x, y) equals the number of non-empty continuous sequences in the list.For example: F(babbabbababbab, babb) = 6. The list of pairs is as follows:(1, 4), (4, 7), (9, 12)Its continuous sequences are:   (1, 4)  (4, 7)  (9, 12)  (1, 4), (4, 7)  (4, 7), (9, 12)  (1, 4), (4, 7), (9, 12) Your task is to calculate for the given string s the sum F(s, x) for all x, that x belongs to the set of all substrings of a string s.

The only line contains the given string s, consisting only of small Latin letters (1 ≤ |s| ≤ 105).

Print the single number — the sought sum. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteIn the first sample the function values at x equal to "a", "aa", "aaa" and "aaaa" equal 10, 6, 3 and 1 correspondingly.In the second sample for any satisfying x the function value is 1.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.io.InputStream;

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

  static class DStroka {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      String s = in.next();
      long answer = new DStroka.Solve(s).solve();
      out.print(answer);
    }

    static long sum(long n) {
      return n * (n + 1) / 2;
    }

    static class Solve {
      int n;
      char[] s;
      int[] order;
      int[] type;
      int[] lcp;

      Solve(String s) {
        s += "$";
        this.s = s.toCharArray();
        n = s.length();
      }

      long solve() {
        initSuffixArray();
        initLCP();
        DS ds = new DS();
        for (int i = 1; i < n; i++) ds.update(i);
        return ds.finish();
      }

      void updateTypes(int len) {
        int[] type2 = new int[n];
        type2[order[0]] = 0;
        for (int i = 1, j = 0; i < n; i++) {
          int left1 = type[order[i]];
          int left2 = type[order[i - 1]];
          int right1 = type[(order[i] + len) % n];
          int right2 = type[(order[i - 1] + len) % n];
          if (left1 != left2 || right1 != right2) j++;
          type2[order[i]] = j;
        }
        System.arraycopy(type2, 0, type, 0, n);
      }

      void countSort(int typeCount, int len) {
        int[] count = new int[typeCount];
        for (int t : type) count[t]++;
        for (int i = 0, j = 0; i < typeCount; i++) {
          int x = count[i];
          count[i] = j;
          j += x;
        }
        int[] order2 = new int[n];
        for (int x : order) order2[count[type[x]]++] = x;
        System.arraycopy(order2, 0, order, 0, n);
        updateTypes(len);
      }

      void initSuffixArray() {
        order = new int[n];
        type = new int[n];
        for (int i = 0; i < n; i++) order[i] = i;
        for (int i = 0; i < n; i++) type[i] = s[i];
        countSort(1 << 8, 0);
        for (int len = 1, typeCount; (typeCount = type[order[n - 1]] + 1) < n; len <<= 1) {
          for (int i = 0; i < n; i++) order[i] = (order[i] - len + n) % n;
          countSort(typeCount, len);
        }
      }

      void initLCP() {
        lcp = new int[n];
        for (int i = 0, k = 0; i < n - 1; i++) {
          int pi = type[i];
          int j = order[pi - 1];
          while (s[i + k] == s[j + k]) k++;
          lcp[pi] = k;
          if (k > 0) k--;
        }
      }

      class DS {
        Deque<IntIntPair> q;
        long total = 0;

        DS() {
          q = new ArrayDeque<>();
          q.add(IntIntPair.makePair(-1, 0));
        }

        void drop(int at) {
          while (q.peekLast().first > at) {
            IntIntPair cur = q.pollLast();
            if (q.peekLast().first == cur.first) {
              q.addLast(IntIntPair.makePair(cur.first, cur.second + q.pollLast().second));
              continue;
            }
            int left = Math.max(q.peekLast().first, at) + 1;
            int right = cur.first;
            int len = right - left + 1;
            total += len * sum(cur.second);
            q.addLast(IntIntPair.makePair(left - 1, cur.second));
          }
        }

        void update(int i) {
          drop(lcp[i] - 1);
          int lastIndex = n - 2 - order[i];
          q.addLast(IntIntPair.makePair(lastIndex, 1));
        }

        long finish() {
          drop(-1);
          return total;
        }

      }

    }

  }

  static class IntIntPair implements Comparable<IntIntPair> {
    public final int first;
    public final int second;

    public static IntIntPair makePair(int first, int second) {
      return new IntIntPair(first, second);
    }

    public IntIntPair(int first, int second) {
      this.first = first;
      this.second = second;
    }

    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      IntIntPair pair = (IntIntPair) o;

      return first == pair.first && second == pair.second;
    }

    public int hashCode() {
      int result = first;
      result = 31 * result + second;
      return result;
    }

    public String toString() {
      return "(" + first + "," + second + ")";
    }

    public int compareTo(IntIntPair o) {
      int value = Integer.compare(first, o.first);
      if (value != 0) {
        return value;
      }
      return Integer.compare(second, o.second);
    }

  }

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

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

    public 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++];
    }

    public String readString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

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

    public String next() {
      return readString();
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void close() {
      writer.close();
    }

    public void print(long i) {
      writer.print(i);
    }

  }
}

[{'input': 'aaaa\r\n', 'output': ['20\r\n']}, {'input': 'abcdef\r\n', 'output': ['21\r\n']}, {'input': 'abacabadabacaba\r\n', 'output': ['188\r\n']}, {'input': 'tkth\r\n', 'output': ['11\r\n']}, {'input': 'eqkrqe\r\n', 'output': ['23\r\n']}, {'input': 'cwuiax\r\n', 'output': ['21\r\n']}, {'input': 'hhhhqhqh\r\n', 'output': ['59\r\n']}, {'input': 'gmxfmcgp\r\n', 'output': ['38\r\n']}, {'input': 'eleellleeee\r\n', 'output': ['104\r\n']}, {'input': 'usussubuubbbbs\r\n', 'output': ['138\r\n']}, {'input': 'lhmpaugvnqzrfxke\r\n', 'output': ['136\r\n']}, {'input': 'xkkkkkkkkkkkkkkkkxkkkk\r\n', 'output': ['1098\r\n']}, {'input': 'pprppppriiriiiirprppprriir\r\n', 'output': ['512\r\n']}, {'input': 'jsoxkutcvyshsinfmtrpujedcbmyqlojzco\r\n', 'output': ['646\r\n']}, {'input': 'emcegmekgnlefkeguqkfffnduqhfhhhndlfhlfdqdncefnn\r\n', 'output': ['1227\r\n']}, {'input': 'ffffdjfddffdjdfffddjfffffffjfffjdjfffjfjfdjjfjdjjdjjjdffd\r\n', 'output': ['2564\r\n']}, {'input': 'cxvhmeyouudwuglhbwndzwmjjsgrnuwnzwaycfspyyrdckjcidfsabvdxzjkvm\r\n', 'output': ['2023\r\n']}, {'input': 'cahdktuxuukmbuqcqactqhqdcxpkqcuumckttdpmpqxxkacpappxuqkxbuahqdphhddhquthqaapm\r\n', 'output': ['3258\r\n']}, {'input': 'hhwhhwhhhwhwwhhwwwhwhhhwhwwwhhwhwhhhhhhwhwhwwwhhwwwhhwhhhhwhwwhwhwwwwhhwwhwhwwwhhhwwhwhwhhwwwhwhhhwwwhwhw\r\n', 'output': ['10856\r\n']}, {'input': 'cnrkvxbljhitbvoysdpghhhnymktvburpvxybnvugkzudmnmpuhevzyjpbtraaepszhhssmcozkgbjayztrvqwdfmjlhtvarkkdsbnjrabqexpfjozmjzfbmdsihovoxmmtjgtfyaisllysnekdxozhdwu\r\n', 'output': ['12399\r\n']}, {'input': 'qasiyhdivaiyyhdqiqsvqhtqsetxqvaeqatxesxehisyqiivhvayaxvsxhsydiesaxydysqhedxqhsqivvidqtsitiiveexiehsqdteahyxtsyqetahviyhqvytexethsqssxiytqhxxxdihxietsyxqhtitheyeateeyhythxhhqaad\r\n', 'output': ['17103\r\n']}, {'input': 'ggwgwwgwwkggwgwwkgwwwggwwwggkgkgwkwgkkgkwwgwkkggwggkwgwgkgwwkwkkkkwggwwkwkkkgwkwwwwwgwkwkkwkggwwgggkkwwkgkgkwgkgkwggkwgggwwkgkwgkwkkgwkkkkggwwwgkggkwwgkwkgwgggkggkkkwwwwwkkgkwggwgkwwwwggwwgkkggwkkwkkgkwggggggkkwkkgkkkwkwwkwggwkkwggggwg\r\n', 'output': ['41166\r\n']}, {'input': 'tmoqyzoikohtgkybnwjizgjypzycmtstmsizrqrmczmqmpewxiwlqzcaufxkchqyjegktxihlksisbgogpyxkltioovelwaqcbebgcyygxsshsirkwvtsvhpqtbomueaszkrlixueyeiccvfiuoogomjlhjkacnxtimkprmjttpmeaminvmcqagrpjighsvaosojymcjoyopsvkrphzbnckcvvckicmjwpvawjuzkofnuvcahwhzjpfngwyobiufivsjnekjcloobvzawrvosnkvalmr\r\n', 'output': ['42165\r\n']}, {'input': 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\r\n', 'output': ['2214420\r\n']}, {'input': 'zzzzooozzzoozozoozzzzzzozooozoozoozzozzozoooozzzzzzoooozzozooozoozzzozozoooooozzzozozooooozozozozzooozozzooozzzzozozoozoozzzozooozzzzoozzzzozzzzoooozozozozozzoooozzzooozzoooooooozozzozozooozzzooooozozooozozzozozoozzozzzzooozzoozozozzozozoozozzzoozozoooozzooozozooooozzzzzoozoozzzozzzoozzoozozzooozzzzzzoozzozzoozzzoozozzooozoozzzozooozozzoozoozozzzzzoozoozzzooooozooooooozooooozzoozoozzzooooozoozozozozzzoozzzzzoozzzzzzooooooozzzzozzozzo\r\n', 'output': ['190205\r\n']}]


You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

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

/*
 * 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 b {

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

        int n = in.nextInt();
        VecL[] a = new VecL[n];

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

        TreeMap<Long, SegL> upper = new TreeMap<>();
        TreeMap<Long, SegL> lower = new TreeMap<>();

        for(int i = 0; i < n; i++) {
            SegL seg = new SegL(a[i], a[(i+1)%n]);
            if(a[i].x < a[(i+1)%n].x || (a[i].x == a[(i+1)%n].x && a[i].y > a[(i+1)%n].y)) upper.put(a[i].x, seg);
            else lower.put(a[i].x, seg);
        }

        int m = in.nextInt();
        for(int i = 0; i < m; i++) {
            VecL vec = new VecL(in.nextInt(), in.nextInt());
            Map.Entry<Long, SegL> upperE = upper.floorEntry(vec.x);
            Map.Entry<Long, SegL> lowerE = lower.ceilingEntry(vec.x);
            if(upperE == null || upperE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
            if(lowerE == null || lowerE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
        }

        System.out.println("YES");

        out.close();
    }

    static class SegL {

        VecL from, to, dir;

        public SegL(VecL from, VecL to) {
            this.from = from;
            this.to = to;
            dir = to.sub(from);
        }

        //check if the segment contains the point
        public boolean contains(VecL p) {
            VecL d = p.sub(from);
            if (d.cross(dir) != 0) {
                return false;
            }
            long dot = d.dot(dir);
            return dot >= 0 && dot <= dir.mag2();
        }

        //(assuming I go left to right)
        //returns:
        //	1 if point is above me
        //	0 if point is on me
        //	-1 if point is below me
        public long side(VecL o) {
            long cross = dir.cross(o.sub(from));
            return cross == 0 ? 0 : cross / Math.abs(cross);
        }

        //returns true if this segl intersects the other, including at endpoints
        //note: returns false if the two segments lie on the same line
        public boolean intersects(SegL o) {
            return side(o.from) != side(o.to) && o.side(from) != o.side(to);
        }

        public String toString() {
            return from + " -> " + to;
        }

        //#
        static long gcd(long a, long b) {
            a = Math.abs(a);
            b = Math.abs(b);
            return b == 0 ? a : gcd(b, a % b);
        }
        //$

        //returns the lattice point of intersection or null if it is nonlattice or does not exist
        public VecL latticeIntersect(SegL o) {
            if (!intersects(o)) {
                return null;
            }
            long dirGCD = gcd(dir.x, dir.y), oDirGCD = gcd(o.dir.x, o.dir.y);
            VecL va= new VecL(dir.x / dirGCD, dir.y / dirGCD), vb = new VecL(o.dir.x / oDirGCD, o.dir.y / oDirGCD);
            if (va.x < 0 && va.y < 0) {
                va.x *= -1;
                va.y *= -1;
            }
            if (vb.x < 0 && vb.y < 0) {
                vb.x *= -1;
                vb.y *= -1;
            }
            if (va.equals(vb)) {
                return null;
            }
            long bottomScalar = va.x / gcd(va.x, va.y);
            long topScalar = va.y / gcd(va.x, va.y);
            long t2Scalar = -bottomScalar * vb.y + topScalar * vb.x;
            long t2Ans = bottomScalar * (o.from.y - from.y) - topScalar * (o.from.x - from.x);
            if (t2Ans % t2Scalar != 0) {
                return null;
            }
            long t2 = t2Ans / t2Scalar;
            return new VecL(t2 * vb.x + o.from.x, t2 * vb.y + o.from.y);
        }
    }

    static class VecL implements Comparable<VecL> {

        long x, y;

        public VecL(long x, long y) {
            this.x = x;
            this.y = y;
        }

        public VecL add(VecL o) {
            return new VecL(x + o.x, y + o.y);
        }

        public VecL sub(VecL o) {
            return new VecL(x - o.x, y - o.y);
        }

        public VecL scale(long s) {
            return new VecL(x * s, y * s);
        }

        public long dot(VecL o) {
            return x * o.x + y * o.y;
        }

        public long cross(VecL o) {
            return x * o.y - y * o.x;
        }

        public long mag2() {
            return dot(this);
        }

        public VecL rot90() {
            return new VecL(-y, x);
        }

        public VecL rot270() {
            return new VecL(y, -x);
        }

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

        public int hashCode() {
            return Long.hashCode(x << 13 ^ (y * 57));
        }

        public boolean equals(Object oo) {
            VecL o = (VecL) oo;
            return x == o.x && y == o.y;
        }

        public int compareTo(VecL o) {
            if (x != o.x) {
                return Long.compare(x, o.x);
            }
            return Long.compare(y, o.y);
        }

        //origin->q1, axes-> quadrant in ccw direction
        public int quadrant() {
            if (x == 0 || y == 0) {
                if (y == 0) {
                    if (x >= 0) {
                        return 1;
                    } else {
                        return 3;
                    }
                } else if (y >= 0) {
                    return 2;
                } else {
                    return 4;
                }
            }
            if (x > 0) {
                if (y > 0) {
                    return 1;
                } else {
                    return 4;
                }
            } else if (y > 0) {
                return 2;
            } else {
                return 3;
            }
        }

        public int radialCompare(VecL o) {
            if (quadrant() == o.quadrant()) {
                return -Long.signum(cross(o));
            }
            return Integer.compare(quadrant(), o.quadrant());
        }
    }

    static class FS {

        BufferedReader in;
        StringTokenizer token;

        public FS(InputStream str) {
            in = new BufferedReader(new InputStreamReader(str));
        }

        public String next() {
            if (token == null || !token.hasMoreElements()) {
                try {
                    token = new StringTokenizer(in.readLine());
                } catch (IOException ex) {
                }
                return next();
            }
            return token.nextToken();
        }

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


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

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

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

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

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

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

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


A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules:  A deck of n cards is carefully shuffled, then all n cards are put on the table in a line from left to right;  Before each move the table has several piles of cards lying in a line (initially there are n piles, each pile has one card). Let's number the piles from left to right, from 1 to x. During one move, a player can take the whole pile with the maximum number x (that is the rightmost of remaining) and put it on the top of pile x - 1 (if it exists) or on the top of pile x - 3 (if it exists). The player can put one pile on top of another one only if the piles' top cards have the same suits or values. Please note that if pile x goes on top of pile y, then the top card of pile x becomes the top card of the resulting pile. Also note that each move decreases the total number of piles by 1;  The solitaire is considered completed if all cards are in the same pile. Vasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not.

The first input line contains a single integer n (1 ≤ n ≤ 52) — the number of cards in Vasya's deck. The next line contains n space-separated strings c1, c2, ..., cn, where string ci describes the i-th card on the table. Each string ci consists of exactly two characters, the first one represents the card's value, the second one represents its suit. Cards on the table are numbered from left to right.  A card's value is specified by one of these characters: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A". A card's suit is specified by one of these characters: "S", "D", "H", "C". It is not guaranteed that the deck has all possible cards. Also, the cards in Vasya's deck can repeat.

On a single line print the answer to the problem: string "YES" (without the quotes) if completing the solitaire is possible, string "NO" (without the quotes) otherwise.

NoteIn the first sample you can act like that:   put the 4-th pile on the 1-st one;  put the 3-rd pile on the 2-nd one;  put the 2-nd pile on the 1-st one. In the second sample there is no way to complete the solitaire.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

public class B208{
	static final boolean FILE_IO = false;
	static final String output_file = "output.txt";
	static final String input_file = "input.txt";

	public static void main(String[] args){
		InputReader in = new InputReader();
		PrintWriter out;
		if(FILE_IO){
			try{
				out = new PrintWriter(output_file);
			} catch(FileNotFoundException e){
				throw new RuntimeException(e);
			}
		} else {
			out = new PrintWriter(System.out);
		}
		final long start = System.currentTimeMillis();
		new Task1().solve(in, out);
		final long duration = System.currentTimeMillis()-start;
		out.close();
	}

	static class Task1{
		static boolean answer=false;
		HashMap<Marker, Boolean> visited;

		static class Marker{
			String last, preLast, prepreLast, preprepreLast;
			Integer size, hash;

			public Marker(int size, String last, String preLast, String prepreLast, String preprepreLast){
				this.size=size;
				this.last=last;
				this.preLast=preLast;
				this.prepreLast=prepreLast;
				this.preprepreLast=preprepreLast;
			}

			public int hashCode(){
				if(hash!=null) return hash;
				hash = size;
				hash = hash*31 + last.hashCode();
				hash = hash*31 + preLast.hashCode();
				hash = hash*31 + prepreLast.hashCode();
				hash = hash*31 + preprepreLast.hashCode();
				return hash;
			}

			public boolean equals(Object temp){
				Marker o = (Marker)temp;
				return(
						size.equals(o.size) &&
						last.equals(o.last) &&
						preLast.equals(o.preLast) &&
						prepreLast.equals(o.prepreLast)
					);
			}
		}

		public void solve(InputReader in, PrintWriter out){
			int n=in.nextInt();
			ArrayList<String> deck = new ArrayList<String>();

			for(int i=0; i<n; i++){
				deck.add(in.next());
			}

			visited = new HashMap<Marker, Boolean>();
			solve(deck);
			if(answer){
				out.println("YES");
			} else {
				out.println("NO");
			}
		}

		boolean match(String a, String b){
			return (a.charAt(0)==b.charAt(0) || a.charAt(1)==b.charAt(1));
		}

		void solve(ArrayList<String> deck){
			int n=deck.size();
			if(n==1 || answer){
				answer=true;
				return;
			}

			if(n>3){
				String last = deck.get(n-1);
				String _preLast = deck.get(n-2);
				String _prepreLast = deck.get(n-3);
				String _preprepreLast = deck.get(n-4);
				Marker mm = new Marker(n, last, _preLast, _prepreLast, _preprepreLast);

				if(visited.containsKey(mm)){
					//System.out.println(n+" "+_preprepreLast+" "+_prepreLast+" "+_preLast+" "+last);
					return;
				}
				visited.put(mm, true);
			}

			if(n>1 && match(deck.get(n-2), deck.get(n-1))){
				ArrayList<String> copy1 = new ArrayList<String>(deck);
				copy1.set(n-2, deck.get(n-1));
				copy1.remove(n-1);
				solve(copy1);
			}

			if(n>3 && match(deck.get(n-4),deck.get(n-1)) ){
				ArrayList<String> copy3 = new ArrayList<String>(deck);
				copy3.set(n-4, deck.get(n-1));
				copy3.remove(n-1);
				solve(copy3);
			}
		}
	}

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

		public InputReader(){
			if(FILE_IO){
				try{
					reader = new BufferedReader(new FileReader(input_file));
				} catch(FileNotFoundException e){
					throw new RuntimeException(e);
				}
			} else {
				reader = new BufferedReader(new InputStreamReader(System.in));
			}
			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 (int)Integer.parseInt(next());
		}

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

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

		public String nextLine(){
			String s = null;
			try{
				s = reader.readLine();
			} catch(Exception e){
				throw new RuntimeException(e);
			}
			return s;
		}
	}
}

[{'input': '4\r\n2S 2S 2C 2C\r\n', 'output': ['YES']}, {'input': '2\r\n3S 2C\r\n', 'output': ['NO']}, {'input': '5\r\n2S 2S 4S 3S 2S\r\n', 'output': ['YES']}, {'input': '5\r\n5S 5S 7S 4S 3H\r\n', 'output': ['NO']}, {'input': '5\r\n7S 7S 4S 8H 4H\r\n', 'output': ['NO']}, {'input': '5\r\n4S 2H 3S 3S 2H\r\n', 'output': ['NO']}, {'input': '52\r\n3H 6S 3S 2S 2S 3S 4S 3H 2C 4S 3C 3S 2S 2C 2S 6S 4C 3S 5C 3S 2S 4S 3S 5S 2H 2S 4H 3S 3S 4H 4S 2C 2H 2S 4S 6D 4C 4H 2H 4S 3H 6D 6S 3C 3C 4H 5S 3S 3S 2H 2S 4C\r\n', 'output': ['NO']}, {'input': '52\r\n2S 4S 3S 2S 4S 3S 4S 4S 8S 3S 2S 2S 5S 3S 3S 2S 3S 5S 4S 4S 2S 2S 4S 4S 6S 2S 5S 2S 5S 2S 2S 2S 4S 2S 5S 5S 2S 6S 8S 6S 2S 2S TS 2H 4S 4S 3S 3S 2S 2S 7S 3S\r\n', 'output': ['YES']}, {'input': '5\r\nAD 5S KH AH AS\r\n', 'output': ['YES']}, {'input': '50\r\nTS 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D 2D\r\n', 'output': ['NO']}, {'input': '5\r\nAD 5S KH AH KS\r\n', 'output': ['YES']}, {'input': '5\r\nAD 5S KH AH JS\r\n', 'output': ['NO']}, {'input': '20\r\nJD 5H 3H 9H 2S 5S 5H QS 8D 7H TS 9S 4H 5S 9H 4H 3S KS KS JS\r\n', 'output': ['NO']}, {'input': '21\r\nJS 5S 9S KH 9D JH 3S KH QH 5D TC 3S 5S 4H 4H 5S 7S AH 4S 3S 6S\r\n', 'output': ['NO']}, {'input': '51\r\nJD 8D QD TC JD AD JD 5D 5S QC TC 4H 8S 7D QD QD 3H TH 8D 9D 5D 4D 6D 7D 9C 2D AD 6D 6H AD 5D 3D AC AC JC 5D 3D KC 7C AD 4D 8C QD QH 6D 9C 2D 6D 3C KC TD\r\n', 'output': ['NO']}, {'input': '52\r\nKD KD 8H 9C 7C 8D JD 3D 9C KD 6D 9C QD TC 7D TD 3C KD 6D 2D TC 6D AC QD 2C 3D 8D KH AD QD 2C 6C JH 6D 8D 2C 7D QD 7C 7H TD 4D 2D 8D TC 5D 8D KD 7C QC TD 5D\r\n', 'output': ['NO']}, {'input': '52\r\nJS 7S 3S 2S 7S TS 4S 6S 5H TS 4S TH 6H 9S TH TH 4S 4H 2H TH TC TH TS TS 4S TS 2S TH TH TS 6S TS TS 3S TS TH 5H TS TS 5S 7H 2H TS 6S 6H 2H TS TH 2S 4S 4H 4S\r\n', 'output': ['YES']}, {'input': '52\r\n8D AD AC 9H AS AD KH AD QH AH AC AS 8H KS TD AH KS AD AD AS KD AD AS AH AS AD AD AH AC AD KC JD 8D AC 9D AC AD QD KC AD JS JC AD TD KC JD TD 8D KS KC KD KD\r\n', 'output': ['YES']}, {'input': '52\r\nAD JD JD TD AD 8D QD AH TC QH AD TD 2D AD QD 4D 3C 3D 3H 6D 8C 3C 3S 6C QC KD 2D 4S TD 5D 3S 3S 3H 3S KH 3H 3D 3H JH JH QH 9H TH 3H KH 7H 3H TH AH 3S 4H 3H\r\n', 'output': ['YES']}, {'input': '10\r\n4C 8C 8D JC 8C 5S 8H 8C 8S 8H\r\n', 'output': ['YES']}, {'input': '10\r\nQH QS QS JH QS 6S 7H QH QH QS\r\n', 'output': ['YES']}, {'input': '10\r\nKS 4S KS KH TS TS KC KH KH KS\r\n', 'output': ['YES']}, {'input': '11\r\nJD 5D JC JH 6C 6D JH 6S 6S JS JD\r\n', 'output': ['YES']}, {'input': '11\r\nJS KH JC JS 9S 9H 6H 7H JH AS AH\r\n', 'output': ['YES']}, {'input': '11\r\n3S 2H TS 9D 9S 2S 2S 9S 3C 2S 2C\r\n', 'output': ['YES']}, {'input': '12\r\n9S TS QS KD KS AS QS KS 6S AD AD AS\r\n', 'output': ['YES']}, {'input': '12\r\nJC 8C AC TH AH AC TC AS AH TC AS AS\r\n', 'output': ['YES']}, {'input': '12\r\n6S 6S 3S 4C 2S 2S 7S 2C 2S 4S 2S 2S\r\n', 'output': ['YES']}, {'input': '51\r\n7S 4C 2S JS 5C 2H 2C 3C 4C QC 2C 2C 2S 4S 2H 2H 4C 2C 6C 2C 2C JC 8C QC JC 8C TC 7H 4C 8S QH 4H 8C 3H 4S 3H 7H 8S 4C 4S 4S 4S 2H 4H QH 3H 3H 3H 4H 8C 3C\r\n', 'output': ['YES']}, {'input': '51\r\n2S 2H 2C 2C 3H 2H 7S 2D 6H 2H 2C 2H 2H 5S 2S 3C 2C 2H 2S 2C 5C JC 2S 4C 3C 2C 5C 4C 4D 8C 5C 6C 7C 4C 4C 6S TS 3C TH 4C 4C TS 7C TC 3C TS TC 2S TH TC 2C\r\n', 'output': ['YES']}, {'input': '52\r\nAC 4C TC 9C TH AD 3C TC 4S 5C TD QD TH 4C 4D 3H TC 4S TH 8H 7H 4D TH QD 4D 8H QH 4D 4H 8D 4H 4D 8H 3D 9D 8H 9D 9C 9H 8D TD 3H 5H 6D QD 9H 6D KD 9H 6D 2D 9D\r\n', 'output': ['YES']}, {'input': '52\r\nJH 8H 9D TH 5H 9H 5H JH 5H 8H 9D QH 9H 6C AD AC 9C AD AH 9C AC 5C 5C AC 5H 5C 8C 5D KD 5H 5C 8D 5D 8D KD 5D QD 8S 8C 8C 8H 8C JD 8C 8D 8C 8H 9C JD 8D 8D JD\r\n', 'output': ['NO']}, {'input': '52\r\n9D AD 9C 6C 9D 7D 6D TS 6D 6D 3D QH 9D 9D 9H 9D 9D 2H 5D JH 9H 5C JC TC 9D 9C 2C 9C 9D 4H 4D AC 9D 4C AC 8C 9C QC 8C 9D 7D QC 9H 9D 2C 9D 9C 3C 7H 9C TC 9H\r\n', 'output': ['NO']}, {'input': '52\r\n9D 5D TC 4D 7D 3D JD 5C 7D TD 5D TD 6H TD TD AD 6D AD TD 2C TD TS TD TD 2H 7D TD QD 2D 2H AC 9D 2D 2C QC AD 2D 4C JC 2D AD 5D 5C AC AD 6C 8D 4D 7C 8C JC AC\r\n', 'output': ['NO']}, {'input': '51\r\nAH 6S 2S 6H 6S 4S 3S 9S 5S 4S 2S 9S 2S 3S 2S JS 2S 2S 9H 2S 9S 2S 3S 9S 4S 4S 9S 9S 2S 2S 3S 2S 6H 7S 3S 3H 6S 3S 2H 6S 3S 6H 7H 6S 6S 4S 4H 5H 4H 4H 6H\r\n', 'output': ['YES']}, {'input': '51\r\nJC 6S 2S 6H 6S 4S 3S 9S 5S 4S 2S 9S 2S 3S 2S JS 2S 2S 9H 2S 9S 2S 3S 9S 4S 4S 9S 9S 2S 2S 3S 2S 6H 7S 3S 3H 6S 3S 2H 6S 3S 6H 7H 6S 6S 4S 4H 5H 4H 4H 6H\r\n', 'output': ['YES']}, {'input': '51\r\n9C 6S 2S 6H 6S 4S 3S 9S 5S 4S 2S 9S 2S 3S 2S JS 2S 2S 9H 2S 9S 2S 3S 9S 4S 4S 9S 9S 2S 2S 3S 2S 6H 7S 3S 3H 6S 3S 2H 6S 3S 6H 7H 6S 6S 4S 4H 5H 4H 4H 6H\r\n', 'output': ['YES']}, {'input': '51\r\n7C 6S 2S 6H 6S 4S 3S 9S 5S 4S 2S 9S 2S 3S 2S JS 2S 2S 9H 2S 9S 2S 3S 9S 4S 4S 9S 9S 2S 2S 3S 2S 6H 7S 3S 3H 6S 3S 2H 6S 3S 6H 7H 6S 6S 4S 4H 5H 4H 4H 6H\r\n', 'output': ['YES']}, {'input': '52\r\n2D 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\n3D 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\nTD 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\nJD 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\nAH 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\n7H 5S 5S JS 5H 5C 5S 5H 2S 5S 9S 3S 2S 5S 2S 2S 5S 4S 3S 5S 7H 3S 5S 7S 4S 2S TS 2S 3S 3S 3S 3S 3S 3S 2S 7S 3S 2S 2S 2S 2S 2S 5S 2H 2C 4S 2S 2S 4S 7S 2S 2S\r\n', 'output': ['YES']}, {'input': '52\r\n2D 5S 4S 4S 4C 2S 4H 4S 4H 4C 3S 4S 4S 4H 5S 4H 4H 5S 2S 4S 4S 2S 4S 4C 4S 4S 9S 4H 4S 3S 3H 4S 4S 7S 3S 3S 2H 3S 7S 4S 2S 7S 2S 2S 3S 3C 2S 3S 3S 2S 5S 3S\r\n', 'output': ['YES']}, {'input': '52\r\nAC 5S 4S 4S 4C 2S 4H 4S 4H 4C 3S 4S 4S 4H 5S 4H 4H 5S 2S 4S 4S 2S 4S 4C 4S 4S 9S 4H 4S 3S 3H 4S 4S 7S 3S 3S 2H 3S 7S 4S 2S 7S 2S 2S 3S 3C 2S 3S 3S 2S 5S 3S\r\n', 'output': ['YES']}, {'input': '52\r\n7D 5S 4S 4S 4C 2S 4H 4S 4H 4C 3S 4S 4S 4H 5S 4H 4H 5S 2S 4S 4S 2S 4S 4C 4S 4S 9S 4H 4S 3S 3H 4S 4S 7S 3S 3S 2H 3S 7S 4S 2S 7S 2S 2S 3S 3C 2S 3S 3S 2S 5S 3S\r\n', 'output': ['YES']}, {'input': '1\r\n3C\r\n', 'output': ['YES']}, {'input': '4\r\n2C 3D 4D 5C\r\n', 'output': ['NO']}]


Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies. Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions:   Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer.  Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that.  Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that.  Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that.  Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that.  Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that.  Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that. Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.

The first line contains integer n (1 ≤ n ≤ 200) — the number of game parts. The next line contains n integers, the i-th integer — ci (1 ≤ ci ≤ 3) represents the number of the computer, on which you can complete the game part number i.  Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0 ≤ ki ≤ n - 1), then ki distinct integers ai, j (1 ≤ ai, j ≤ n; ai, j ≠ i) — the numbers of parts to complete before part i. Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.

On a single line print the answer to the problem.

NoteNote to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours.

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

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

class TaskA {

    private int n;
    private int[] completeOn;
    private int[] degIn;
    private boolean[][] g;

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        n = in.nextInt();
        completeOn = Utils.readIntArray(in, n);
        degIn = new int[n];
        g = new boolean[n][n];
        for (int i = 0; i < n; ++i) {
            int am = in.nextInt();
            for (int j = 0; j < am; ++j) {
                int x = in.nextInt()-1;
                g[x][i] = true;
                degIn[i]++;
            }
        }
        int res = Integer.MAX_VALUE;
        for (int i = 1; i <= 3; ++i) {
            res = Math.min(res, process(i));
        }
        out.println(res);
    }

    private int process(int cur) {
        boolean[] visited = new boolean[n];
        int cost = 0;
        int[] curDegIn = degIn.clone();
        while (true) {
            boolean finished = true;
            List<Integer> queue = new ArrayList<Integer>();
            for (int i = 0; i < n; ++i) {
                if (!visited[i]) {
                    finished = false;
                    if (curDegIn[i] == 0 && completeOn[i] == cur) {
                        queue.add(i);
                    }
                }
            }
            if (finished) break;
            if (queue.size() == 0) {
                cur++;
                ++cost;
                if (cur == 4) {
                    cur = 1;
                }
                continue;
            }
            for (int x : queue) {
                ++cost;
                visited[x] = true;
                for (int i = 0; i < n; ++i) {
                    if (g[x][i]) {
                        --curDegIn[i];
                    }
                }
            }
        }
        return cost;
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer stt;

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

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

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

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

}

class Utils {
    public static int[] readIntArray(InputReader in, int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; ++i) {
            a[i] = in.nextInt();
        }
        return a;
    }

}


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

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

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

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

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

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

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

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

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

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

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

    }

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

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

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

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

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

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

            return res.toString();
        }

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

    }
}