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

class Main{
        static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public static void main(String[] args) throws IOException{
                int num = Integer.parseInt(br.readLine());
                Deque<String> ar = new ArrayDeque<>(num);
                for(int i=0; i<num; i++){
                        int val;
                        String strs = br.readLine();
                        if(strs.charAt(0) == 'i')
                                ar.addFirst(strs.substring(7));
                        else if(strs.charAt(6) == 'F')
                                ar.removeFirst();
                        else if(strs.charAt(6) == 'L')
                                ar.removeLast();
                        else
                                ar.remove(strs.substring(7));
                }
                String j = ar.poll();
                while(j != null){
                        System.out.print(j);
                        j = ar.poll();
                        if(j!=null)
                                System.out.print(" ");
                }
                System.out.println();
        }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;

class Main {
    public static void main(String[] args) throws IOException {
        Deque<Integer> lnk=new LinkedList<Integer>();
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        for(int i=0;i<n;i++){
            String s=br.readLine();

            if(s.equals("deleteFirst"))lnk.remove();
            else if(s.equals("deleteLast"))lnk.removeLast();
            else{
                if(s.startsWith("insert"))lnk.addFirst(Integer.parseInt(s.substring(7)));
            else if(s.startsWith("delete")) lnk.remove(Integer.parseInt(s.substring(7)));
            }
        }StringBuilder stb=new StringBuilder(Integer.toString(lnk.poll()));
        for(Integer i:lnk)stb.append(" "+i);
        System.out.println(stb);}

    }

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		String str = stdIn.next();
		int len = str.length();
		int[] level = new int[len+1];
		int top = 0;
		int bottom = 0;
		int nowLevel = 0;

		for (int i=0; i<len; i++) {
			char c = str.charAt(i);
			level[i] = nowLevel;
			if (c == '\' || c == '\\') {
				nowLevel--;
			}else if(c == '/'){
				nowLevel++;
			}
			top = Math.max(top,nowLevel);
			bottom = Math.min(bottom,nowLevel);
		}
		level[len] = nowLevel;
		top = Math.max(top,nowLevel);
		bottom = Math.min(bottom,nowLevel);

		boolean[] water = new boolean[len];
		Map<Integer,Integer> map = new HashMap<Integer,Integer>();
		int sum = 0;

		for (int i=top; i>bottom; i--) {//高さ
			int start = -1;
			for (int j=0; j<len; j++) {//幅
				if (!water[j]) {//水は入っているか
					if ((start==-1?level[j]:level[j+1]) == i) {//levelの一致
						if (start == -1 && level[j]>level[j+1]) {//startが設定されているか '\'であるか
							start = j;
						}else if(start != -1){
							int count = 0;//傾斜数
							int vol = 0;
							for (int k=start; k<j+1; k++) {//面積計算
								vol += Math.abs(level[start] - Math.max(level[k],level[k+1]));
								if(Math.abs(level[k] - level[k+1]) > 0)
									count++;
								water[k] = true;//水を入れる
							}
							vol += count/2;
							sum += vol;//総面積に足す
							map.put(start,vol);
							start = -1;
						}
					}
				}
			}
		}

		System.out.println(sum);
		System.out.print(map.size());
		for (int i=0; map.size()!=0; i++) {
			if(map.containsKey(i)){
				System.out.print(" "+map.get(i));
				map.remove(i);
			}
		}
		System.out.println();
	}
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

For a given cross-section diagram, reports areas of flooded sections.

Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

In the first line, print the total area $A$ of created floods.

In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9


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

public class Main {
	static Slope[] data;
	static int[] height;
	static boolean[] mount;

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

		String input = sc.next();
//		System.out.println(input);
		data = new Slope[input.length()];
		for (int i = 0; i < data.length; i++) {
			char temp = input.charAt(i);
			switch (temp) {
				case '\\':
					data[i] = Slope.DOWN;
					break;
				case '/':
					data[i] = Slope.UP;
					break;
				case '_':
					data[i] = Slope.FLAT;
					break;
				default:
					assert true;
			}
		}

		height = new int[data.length + 1];
		height[0] = 0;
		mount = new boolean [data.length + 1];
		Slope prev = Slope.UP;
		for (int i = 0; i < data.length; i++) {
			height[i + 1] = height[i] + data[i].height;
			if (prev == Slope.UP && data[i] == Slope.DOWN) {
				mount[i] = true;
			}
			if (data[i] != Slope.FLAT) {
				prev = data[i];
			}
		}
		if ( prev == Slope.UP) {
			mount[data.length] = true;
		}

//		for (int i = 0; i < height.length; i++) {
//			System.out.println(height[i] + ":" + mount[i]);
//		}

		ArrayList<Integer> result = new ArrayList<Integer>();
		for (int i = 0; i < height.length; ) {
			int from = nextMount(i);
			int to = nextMount(from + 1);
			if (from == -1) {
				break;
			}
			if (to == -1) {
				i++;
				continue;
			}
			result.add(getSquare(from, to));
			i = to;
		}

		int sum = 0;
		StringBuffer str = new StringBuffer();
		str.append(result.size());
		for (int i = 0; i < result.size(); i++) {
			sum += result.get(i);
			str.append(" ");
			str.append(result.get(i));
		}
		System.out.println(sum);
		System.out.println(str);

		sc.close();
	}

	private static int nextMount(int start) {
		for (int i = start; i < mount.length; i++) {
			if (mount[i] == true) {
				return i;
			}
		}

		return -1;
	}

	private static int getSquare(int from, int to) {
		int min = Math.min(height[from], height[to]);
		int square = 0;
		for (int i = from; i < to; i++) {
			if (height[i] > min || height[i + 1] > min) {
				continue;
			}
			square += (min - height[i] + min - height[i + 1]);
		}
		return square / 2;
	}

	private static enum Slope {
		DOWN(-1), UP(1), FLAT(0);

		int height;
		Slope(int height) {
			this.height = height;
		}
	}
}


import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main{
//	private int LinearSearch(int[] a1, int[] a2) {
//
//	}
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		Set<Integer> set1 = new HashSet<>();
		for (int i = 0; i < n; ++i)
			set1.add(scan.nextInt());
		int q = scan.nextInt();
		Set<Integer> set2 = new HashSet<>();
		for (int i = 0; i < q; ++i)
			set2.add(scan.nextInt());
//		set1.retainAll(set2);//求共同元素
//		//返回值表示set1的内存发生改变，s两者可能没有公共元素，set1变成空集
//		System.out.println(set1.size());
		int sum = 0;
		for(int i : set1)
			for (int j : set2) {
				if(i == j)
					sum++;
			}
		System.out.println(sum);

	}

}

Search I

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

n ≤ 10000

q ≤ 500

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
3 1 2
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


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

public class Main {

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

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

		int q = sc.nextInt();
		int[] t = new int[q];
    	for (int i = 0; i < q; i++) {
    		t[i] = sc.nextInt();
    	}

    	Arrays.sort(s);
    	Arrays.sort(t);

    	int count = 0;
    	for (int i = 0, key = 0; i < n && key < q;) {
    		if (s[i] < t[key]) {
    			i++;
    		} else if (s[i] == t[key]) {
    			count++;
    			i++;
    			key++;
//    			System.out.println(s[i]);
    		} else {
    			key++;
    		}
    	}

    	System.out.println(count);

    	sc.close();
	}
}

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


import java.util.Scanner;

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

        int n = sc.nextInt();
        int[] s = new int[n + 1];
        for(int i = 0 ; i < n; i++) {
            s[i] = sc.nextInt();
        }
        int q = sc.nextInt();
        int[] t = new int[q];
        for(int i = 0; i < q; i++) {
            t[i] = sc.nextInt();
        }

        int ans = 0;
        for(int i = 0; i < q; i++) {
            if(binarySerch(s, n, t[i])) ans++;
        }

        System.out.println(ans);

        sc.close();
    }

    private static boolean binarySerch(int[] a, int n, int key) {
        int left = 0;
        int right = n;
        while(left < right) {
            int mid = (left + right) / 2;
            if(a[mid] == key) {
                return true;
            }else if(key < a[mid]) {
                right = mid;
            }else {
                left = mid + 1;
            }
        }

        return false;
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * ZAKIREN第5章 4-6.データ構造の応用
 *
 * @author tdi5277
 *
 */
public class Main {
	/** 入力用 */
	private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

	/** 出力用 */
	private static StringBuilder stringBuilder = new StringBuilder();

	/**
	 * トラックの積載量をチェック。
	 */
	private static int check(int p, int k, int[] w, int n) {
		int i = 0;
		// truckの数だけループ
		for (int j = 0; j < k; j++) {
			// max積載量になるまで
			int internalCapacity = 0;
			while (internalCapacity + w[i] <= p) {
				// 内容量を増やす
				internalCapacity += w[i];
				i++;

				// 全ての積載量を積むことができた場合
				if (i == n) {
					return n;
				}
			}
		}
		return i;
	}

	/**
	 * メイン。
	 *
	 * @param args 未使用
	 */
	public static void main(String[] args) {
		try {
			final String SPACE = " ";
			// 読み込み
			String[] temp = bufferedReader.readLine().split(SPACE);
			int n = Integer.parseInt(temp[0]);
			int k = Integer.parseInt(temp[1]);

			// n回ループ
			int[] w = new int[n];
			for (int i = 0; i < n; i++) {
				w[i] = Integer.parseInt(bufferedReader.readLine());
			}

			// 読み込み終了
			bufferedReader.close();
			bufferedReader = null;

			// 二分探索法でPを求める
			int left = 0;
			int right = n * 10000;
			int mid = 0;
			while (right - left > 1) {
				mid = (left + right) / 2;
				// そのPで積み込みきれるかチェック
				int size = check(mid, k, w, n);
				if (size >= n) {
					right = mid;
				} else {
					left = mid;
				}
			}
			stringBuilder.append(right);

			// 結果出力
			System.out.println(stringBuilder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


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

class Main{
    static int n = 0;
    static int[] merge(int[] A,int left,int mid,int right){
        int count = A.length;
        int[] Acopy = new int[count];
        count = left;
        int current = mid + 1;

        for(int i = left; i <= right; i++){
            Acopy[i] = A[i];
        }
        while(left <= mid && current <= right){
            if(Acopy[left] <= Acopy[current]){
                A[count] = Acopy[left];
                left++;
            }else{
                A[count] = Acopy[current];
                current++;
            }
            count++;
            n++;
        }

        for(int i = 0; i <= (mid - left); i++){
            A[count + i] = Acopy[left + i];
        }
        return A;

        // int n1 = mid - left + 1;
        // int n2 = right - mid + 1;
        // int[] L = new int[n1];
        // int[] R = new int[n2];
        // int i, j, k, count;

        // System.out.println("left is " + left);
        // System.out.println("right is " + right);
        // System.out.println("mid is " + mid);

        // for(i = 0; i < A.length; i++){
        //     System.out.print(A[i] + " ");
        // }
        // System.out.println();

        // for(i = 0; i < n1 - 1; i++){
        //     L[i] = A[left + i];
        //     System.out.print(L[i] + " ");
        // }

        // System.out.println();

        // for(i = 0; i < n2 - 1; i++){
        //     R[i] = A[mid + i];
        //     System.out.print(R[i] + " ");
        // }

        // System.out.println();

        // L[n1 - 1] = Integer.MAX_VALUE;
        // R[n2 - 1] = Integer.MAX_VALUE;

        // i = 0;
        // j = 0;

        // for(k = left; k < right - 1; k++){
        //     if(L[i] <= R[j]){
        //         A[k] = L[i];
        //         i = i + 1;
        //     }else{
        //         A[k] = R[j];
        //         j = j + 1;
        //     }
        // }

        // //
        // for(i = 0; i < A.length; i++){
        //     System.out.print(A[i] + " ");
        // }
        // System.out.println();
        // //
        // // count = k;

        // // for(k = 0; k < n1; k++){
        // //     A[count + i] = A[left];
        // // }

        // System.out.println("----------OK");
        // return A;
    }

    static int[] mergeSort(int[] A,int left,int right, int count){
        int[] sortArray = new int[count];
        // System.out.println("--left is " + left);
        // System.out.println("--right is " + right);

        if(left < right){
            n++;
            int mid  = (left + right) / 2;
            mergeSort(A, left, mid, count);
            mergeSort(A, mid + 1, right, count);
            sortArray = merge(A, left, mid, right);
        }
        return sortArray;
    }

    public static void main(String[] args){
        int count1;
        int[] array1;
        int count;

        try{
            Scanner scan = new Scanner(System.in);
            String str;

            str= scan.next();
            count1 = Integer.parseInt(str);
            array1 = new int[count1];

            for(int i = 0; i < array1.length; i++){
                str = scan.next();
                array1[i] = Integer.parseInt(str);
            }
            // System.out.println("OK1");
            array1 = mergeSort(array1, 0, count1 - 1, count1);
            // System.out.println("OKlast");
            for(int i = 0; i < array1.length; i++){
                if(i == array1.length - 1){
                    System.out.println(array1[i]);
                }else{
                    System.out.print(array1[i] + " ");
                }
            }

            System.out.println(n);

        }catch(Exception e){
            System.out.println("ERROR " + e);
        }

    }
}

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


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

public class Main {

    static final int MAX_A = 10000 + 10;
    static int n;

    public static void main(String[] args) throws IOException{
        Scanner sc = new Scanner(System.in);
        n = Integer.parseInt(sc.next());

        int[] A = new int[n + 10];
        for (int i = 0; i < n; i++) {
            A[i] = Integer.parseInt(sc.next());
        }

        int[] B = new int[n + 10];
        CountingSort(A, B);

        String ans = "";
        for (int i = 0; i < n; i++) {
            ans += String.format("%d ", B[i]);
        }
        System.out.println(ans.trim());
    }

    static void CountingSort(int[] A, int[] B) {
        int[] C = new int[MAX_A];

        for (int i = 0; i < n; i++) {
            C[A[i]]++;
        }

        for (int i = 1; i < MAX_A; i++) {
            C[i] += C[i - 1];
        }

        for (int i = n - 1; i >= 0; i--) {
            C[A[i]]--;
            B[C[A[i]]] = A[i];
        }
    }

    public static class Scanner {
        private BufferedReader br;
        private StringTokenizer tok;

        public Scanner(InputStream is) throws IOException {
            br = new BufferedReader(new InputStreamReader(is));
        }

        private void getLine() throws IOException {
            while (!hasNext()) { tok = new StringTokenizer(br.readLine()); }
        }

        private boolean hasNext() {
            return tok != null && tok.hasMoreTokens();
        }

        public String next() throws IOException {
            getLine(); return tok.nextToken();
        }

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

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

        public void close() throws IOException {
            br.close();
        }
    }
}

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


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

public class Main {

	public static void countingSort(int[] a, int[] b, int k, int n){
		int[] c = new int[k + 1];

		for(int i = 0; i < n; i++) {
			c[a[i]]++;
		}

		for(int i = 1; i < k + 1; i++) {
			c[i] = c[i] + c[i - 1];
		}

		for(int i = n - 1; i >= 0; i--) {
			b[c[a[i]] - 1] = a[i];
			c[a[i]]--;
		}
	}

	public static void main(String[] args) throws NumberFormatException, IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int ElementCount = Integer.parseInt(br.readLine());

		String[] c = br.readLine().split(" ");

		int[] cInt = new int[ElementCount];

		int cIntMaxNum = 0;
		for(int i = 0; i < ElementCount; i++) {
			cInt[i] = Integer.parseInt(c[i]);
			cIntMaxNum = Math.max(cIntMaxNum, cInt[i]);
		}

		int[] cIntSort = new int[ElementCount];

		countingSort(cInt, cIntSort, cIntMaxNum, ElementCount);

		StringBuilder sb = new StringBuilder();

		for(int i = 0; i < cIntSort.length; i++) {
			sb.append(cIntSort[i]);
			if(i == cIntSort.length - 1){
				break;
			}
			sb.append(" ");
		}
		System.out.println(sb.toString());
	}
}


import java.util.Scanner;
import java.util.Arrays;
import static java.util.stream.Collectors.joining;

class Main {
  final static int k = 10001;
  static int[] C = new int[k];

  public static void main(String... args) {
    Scanner sc = new Scanner(System.in);
    int size = sc.nextInt();
    int current = 0;
    int[] A = new int[size];
    int[] B = new int[size];

    for (int i = 0; i < size; i++) C[A[i] = Integer.parseInt(sc.next())]++;
    for (int i = 1; i < k; i++) C[i] += C[i - 1];
    for (int i = size - 1; i >= 0; i--) B[--C[A[i]]] = A[i];
    System.out.println(Arrays.stream(B).boxed().map(n -> n.toString()).collect(joining(" ")));
  }
}


import java.util.Scanner;

public class Main{
    public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int A[]= new int[n];
    for(int i=0; i<n; i++){
        A[i] = sc.nextInt();
    }
    int q = partition(A, 0, n-1);
    for(int i=0; i<n; i++){
        if(i!=0) System.out.print(" ");
        if(i==q) System.out.print("[");
        System.out.print(A[i]);
        if(i==q) System.out.print("]");
    }
    System.out.println();
    }

    public static int partition(int A[], int p, int r){
    int t;
    int x = A[r];
    int i = p-1;
    for(int j=p; j<r; j++){
        if(A[j]<=x){
        i++;
        t = A[i]; A[i] = A[j]; A[j] = t;
        }
    }
    t = A[i+1]; A[i+1] = A[r]; A[r] = t;
    return i+1;
    }
}

Partition

Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.

In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).

Your task is to read a sequence A and perform the Partition based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].

Input

The first line of the input includes an integer n, the number of elements in the sequence A.

In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [  ].

Constraints

1 ≤ n ≤ 100,000

0 ≤ Ai ≤ 100,000

Sample Input 1

12
13 19 9 5 12 8 7 4 21 2 6 11

Sample Output 1

9 5 8 7 4 2 6 [11] 21 13 19 12


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

public class Main{
	public static int max = 0;
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String[][] str = new String[n][2];
		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i<n ; i++) {
			String line = br.readLine();
			list.add(line);
			str[i] = line.split(" ");
		}
		String[] mark = new String[n];
		int[] num = new int[n];

		for (int i = 0; i<n ; i++ ) {
			mark[i] = str[i][0];
			num[i] = Integer.parseInt(str[i][1]);
		}

		quicksort(mark,num,0,n-1);

		int i = 1;
		while( i <= num[n-1] ){
			int search = 0;
			for (int j = 0; j<n ; j++ ) {
				if (num[j] == i) {
					int r = list.indexOf(mark[j] + " " + num[i]);
					if (search > r) {
						System.out.println("Not stable");
						i = num[n-1] + 1;
						break;
					}else{
						search = r;
					}
				}
			}
			i++;
			if ( i == num[n-1] + 1) {
				System.out.println("Stable");
			}
		}
		for (int k = 0; k<n ; k++ ) {
			System.out.println(mark[k] + " " + num[k]);
		}

	}

	public static void quicksort(String[] st,int[] a,int p,int r){
		if(p < r){
			int q = partition(st,a,p,r);
			quicksort(st,a,p,q-1);
			quicksort(st,a,q+1,r);
		}
	}

	public static int partition(String[] st,int[] a ,int p,int r){
		int x = a[r];
		int i = p-1;
		for (int j = p; j<r ; j++ ) {
			if (a[j] <= x)  {
				i++;
				int work = a[i];
				a[i] = a[j];
				a[j] = work;

				String workst = st[i];
				st[i] = st[j];
				st[j] = workst;
			}
		}
		int num = a[i+1];
		a[i+1] = a[r];
		a[r] = num;

		String str = st[i+1];
		st[i+1] = st[r];
		st[r] = str;
		return i+1;
	}

	public static void printing(int[] a){
		for (int i = 0; i<a.length ; i++ ) {
			if (i == a.length-1) {
				System.out.println(a[i]);
			}else{
				System.out.print(a[i] + " ");
			}
		}
	}
}

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


import java.util.Scanner;

public class Main {
	private int[] a;
	private String[] ori;
	private String[] se;

	private Scanner sc;

	public static void main(String[] args) {
		new Main();
	}

	public Main() {
		sc = new Scanner(System.in);
		int lim = Integer.parseInt(sc.nextLine());

		a = new int[lim];
		ori = new String[lim];
		se = new String[lim];
		for (int i = 0; i < lim; i++) {
			ori[i] = sc.nextLine();
			se[i] = ori[i];
			a[i] = Integer.parseInt(se[i].split(" ")[1]);
		}
		quickSort(0, (lim - 1));

		boolean flag = true;
		int scope = a[0];
		for (int i = 0; i < lim; i++) {
			for (int j = 0; j < lim; j++) {
				if (se[i].equals(ori[i]) && (i != (lim - 1))) {
					if (scope == a[i + 1]) {
						i++;
					} else {
						break;
					}
				}
			}
			if (i != (lim - 1)) {
				if (scope == a[i + 1]) {
					flag = false;
					break;
				}
			}
		}
		if (flag) System.out.println("Stable");
		else System.out.println("Not stable");

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < lim; i++) {
			sb.append(se[i] + "\n");
		}
		System.out.print(sb);
	}

	private void quickSort(int p, int r) {
		if (p < r) {
			int q = partition(p, r);
			quickSort(p, (q - 1));
			quickSort((q + 1), r);
		}

	}

	private int partition(int p, int r) {
		int x = a[r];
		int i = p - 1;

		int tmp;
		String stmp;

		for (int j = p; j < r; j++) {
			if (a[j] <= x) {
				i = i + 1;

				tmp = a[i];
				stmp = se[i];

				a[i] = a[j];
				se[i] = se[j];

				a[j] = tmp;
				se[j] = stmp;
			}
		}

		tmp = a[i + 1];
		stmp = se[i + 1];

		a[i + 1] = a[r];
		se[i + 1] = se[r];

		a[r] = tmp;
		se[r] = stmp;
		return (i + 1);
	}
}


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

class Cards{
    char symbol;
    int num;
    int index;
}

//I have to use hashset
public class Main{
    static int count =0;
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;

        str = br.readLine();
        int n = Integer.parseInt(str);

        Cards A[] = new Cards[n];
        for(int i=0;i<n;i++){
            A[i] = new Cards();
        }

        for(int i=0;i<n;i++){
            str=br.readLine();
            String[] line = str.split("\\s");
            A[i].symbol = line[0].charAt(0);
            A[i].num = Integer.parseInt(line[1]);
            A[i].index = i;
        }

        quicks(A,0,n-1);
        //Stable 判定考える
        boolean flag = judge(A);

        if(flag){
            System.out.println("Stable");
        }else{
            System.out.println("Not stable");
        }

        for(int i=0;i<n;i++){
            System.out.print(A[i].symbol + " " + A[i].num);
            if(i != A.length-1){
                System.out.print("\n");
            }
        }
    }

    public static boolean judge(Cards[]A){
        for(int i=0;i<A.length;i++){
            for(int j=i+1;j<A.length;j++){
                if(A[i].num == A[j].num && A[i].index > A[j].index){
                    return false;
                }
            }
        }
        return true;
    }

    public static int partition(Cards[]A,int p,int r){
        int x = A[r].num;
        int i= p -1;
        for(int j= p;j<r;j++){
            if(A[j].num <= x){
                i++;
                Cards tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }

        Cards change = A[r];
        A[r] = A[i+1];
        A[i+1] = change;

        return i+1;
    }

    public static void quicks(Cards[]A,int p,int r){
        if(p < r){
            int q = partition(A,p,r);
            quicks(A,p,q-1);
            quicks(A,q+1,r);
        }
    }
}


import java.util.Scanner;

class Node{
	int id;
	int parent, left, right;
	public Node(int id){
		this.id = id;
		this.parent = -1;
		this.left = -1;
		this.right = -1;
	}
}
class Nodes{
	Node[] nodes;
	public int getDepth(int id){
		int d = 0;
		int u = nodes[id].parent;
		while(u != -1){
			u = nodes[u].parent;
			d++;
		}
		return d;
	}
	public void printChildren(int id){
		int c = nodes[id].left;
		while(c!=-1){
			System.out.print(c);
			c = nodes[c].right;
			if(c!=-1) System.out.print(", ");
		}
	}
	public void printNode(int id){
		System.out.print("node " + id + ": ");
		System.out.print("parent = " + nodes[id].parent + ", ");
		System.out.print("depth = " + getDepth(id) + ", ");
		if(nodes[id].parent == -1)
			System.out.print("root, ");
		else if(nodes[id].left == -1)
			System.out.print("leef, ");
		else
			System.out.print("internal node, ");
		System.out.print("[");
		printChildren(id);
		System.out.println("]");
	}
}
public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();

		Nodes mynodes = new Nodes();
		Node[] nodes = new Node[n];
		mynodes.nodes = nodes;
		for(int i = 0;i<n;i++){
			nodes[i] = new Node(i);
		}
		int l = 0;
		for(int i=0;i<n;i++){
			int id = in.nextInt();
			int k = in.nextInt();
			for(int j=0;j<k;j++){
				int c = in.nextInt();
				if(j==0){
					nodes[id].left = c;
					l = c;
				}
				//????????????????????????
				else nodes[l].right = c;
				l = c;
				nodes[c].parent = id;
			}
		}
		for(int j=0;j<n;j++){
			mynodes.printNode(j);
		}
	}
}

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

4
1 3 3 2 0
0 0
3 0
2 0

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		ContestScanner scan = new ContestScanner();

		final int n = scan.nextInt();
		final Node[] nodes = new Node[n];

		for(int i=0; i < n; i++)
		{
			nodes[i] = new Node(scan.nextInt(), scan.nextInt(), scan.nextInt());
		}

		(new Solve(n, nodes)).solve();
	}
}
class Solve {
	private final int n;
	private final Node[] nodes;

	public Solve(final int n, final Node[] nodes)
	{
		this.n = n;
		this.nodes = nodes;
	}

	public void solve()
	{
		Node[] nodeMap = new Node[n];
		Node[] childMap = new Node[n];

		for(int i=0; i < n; i++)
		{
			Node n = nodes[i];
			nodeMap[n.id] = n;
			if(n.l != -1) childMap[n.l] = n;
			if(n.r != -1) childMap[n.r] = n;
		}

		Node root = null;

		for(int i=0; i < n; i++)
		{
			if(childMap[nodes[i].id] == null)
			{
				root = nodeMap[nodes[i].id];
				break;
			}
		}

		StringBuilder sb = new StringBuilder();

		sb.append("Preorder \n");
		walkPreorder(n, nodes, nodeMap, childMap, root, sb);
		sb.append(" \n");
		sb.append("Inorder \n");
		walkInorder(n, nodes, nodeMap, childMap, root, sb);
		sb.append(" \n");
		sb.append("Postorder \n");
		walkPostorder(n, nodes, nodeMap, childMap, root, sb);
		System.out.println(sb.toString());
	}

	private void walkPreorder(final int n, final Node[] nodes,
								final Node[] nodeMap, final Node[] childMap,
											final Node node, final StringBuilder sb)
	{
		sb.append(" " + node.id);
		if(node.l != -1) walkPreorder(n, nodes, nodeMap, childMap, nodeMap[node.l], sb);
		if(node.r != -1) walkPreorder(n, nodes, nodeMap, childMap, nodeMap[node.r], sb);
	}

	private void walkInorder(final int n, final Node[] nodes,
								final Node[] nodeMap, final Node[] childMap,
											final Node node, final StringBuilder sb)
	{
		if(node.l != -1) walkInorder(n, nodes, nodeMap, childMap, nodeMap[node.l], sb);
		sb.append(" " + node.id);
		if(node.r != -1) walkInorder(n, nodes, nodeMap, childMap, nodeMap[node.r], sb);
	}

	private void walkPostorder(final int n, final Node[] nodes,
								final Node[] nodeMap, final Node[] childMap,
											final Node node, final StringBuilder sb)
	{
		if(node.l != -1) walkPostorder(n, nodes, nodeMap, childMap, nodeMap[node.l], sb);
		if(node.r != -1) walkPostorder(n, nodes, nodeMap, childMap, nodeMap[node.r], sb);
		sb.append(" " + node.id);
	}
}
class Node {
	public final int id;
	public final int l;
	public final int r;

	public Node(final int id, final int l, final int r)
	{
		this.id = id;
		this.l = l;
		this.r = r;
	}
}
class ContestScanner {
	BufferedReader reader;
	String[] line;
	int index;
	public ContestScanner() {
		reader = new BufferedReader(new InputStreamReader(System.in));
	}

	public ContestScanner(String filename) throws FileNotFoundException {
		reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
	}

	public static interface ICreator<T> {
		public T createFromToken(final ContestScanner scanner) throws IOException;
	}

	public static interface IArrayInitializer {
		public void initialize(final ContestScanner scanner, final int i) throws IOException;
	}

	public static interface IObjectInitializer<T> {
		public T initialValue(final ContestScanner scanner);
	}

	public static class ObjectArrayInitializer<T> implements IArrayInitializer {
		protected T[] arr;
		protected final IObjectInitializer<T> initializer;

		private ObjectArrayInitializer(T[] arr, final IObjectInitializer<T> initializer)
		{
			this.arr = arr;
			this.initializer = initializer;
		}

		public static <T> ObjectArrayInitializer<T> create(T[] arr, final IObjectInitializer<T> initializer)
		{
			return new ObjectArrayInitializer<T>(arr, initializer);
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = initializer.initialValue(scanner);
		}

		public T[] getArray()
		{
			return this.arr;
		}
	}

	public static class ByteArrayInitializer implements IArrayInitializer {
		protected byte[] arr;

		private ByteArrayInitializer(final int n)
		{
			this.arr = new byte[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextByte();
		}

		public byte[] getArray()
		{
			return this.arr;
		}
	}

	public static class ShortArrayInitializer implements IArrayInitializer {
		protected short[] arr;

		private ShortArrayInitializer(final int n)
		{
			this.arr = new short[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextShort();
		}

		public short[] getArray()
		{
			return this.arr;
		}
	}

	public static class IntArrayInitializer implements IArrayInitializer {
		protected int[] arr;

		private IntArrayInitializer(final int n)
		{
			this.arr = new int[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextInt();
		}

		public int[] getArray()
		{
			return this.arr;
		}
	}

	public static class LongArrayInitializer implements IArrayInitializer {
		protected long[] arr;

		private LongArrayInitializer(final int n)
		{
			this.arr = new long[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextLong();
		}

		public long[] getArray()
		{
			return this.arr;
		}
	}

	public static class FloatArrayInitializer implements IArrayInitializer {
		protected float[] arr;

		private FloatArrayInitializer(final int n)
		{
			this.arr = new float[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextFloat();
		}

		public float[] getArray()
		{
			return this.arr;
		}
	}

	public static class DoubleArrayInitializer implements IArrayInitializer {
		protected double[] arr;

		private DoubleArrayInitializer(final int n)
		{
			this.arr = new double[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextDouble();
		}

		public double[] getArray()
		{
			return this.arr;
		}
	}

	public String nextToken() throws IOException {
		if(line == null || index >= line.length)
		{
			line = reader.readLine().trim().split(" ");
			index = 0;
		}

		return line[index++];
	}

	public String next() throws IOException {
		return nextToken();
	}

	public String readLine() throws IOException {
		line = null;
		index = 0;

		return reader.readLine();
	}

	public byte nextByte() throws IOException, NumberFormatException {
		return Byte.parseByte(nextToken());
	}

	public short nextShort() throws IOException, NumberFormatException {
		return Short.parseShort(nextToken());
	}

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

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

	public float nextFloat() throws IOException, NumberFormatException {
		return Float.parseFloat(nextToken());
	}

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

	public <T> T nextObject(final ICreator<T> creator) throws IOException, NumberFormatException {
		return creator.createFromToken(this);
	}

	public int[] nextIntArray(final int N) throws IOException, NumberFormatException {
		int[] result = new int[N];

		for(int i=0; i < N; i++) result[i] = nextInt();

		return result;
	}

	public long[] nextLongArray(final int N) throws IOException, NumberFormatException {
		long[] result = new long[N];

		for(int i=0; i < N; i++) result[i] = nextLong();

		return result;
	}

	public float[] nexFloatArray(final int N) throws IOException, NumberFormatException {
		float[] result = new float[N];

		for(int i=0; i < N; i++) result[i] = nextFloat();

		return result;
	}

	public double[] nexDoubleArray(final int N) throws IOException, NumberFormatException {
		double[] result = new double[N];

		for(int i=0; i < N; i++) result[i] = nextDouble();

		return result;
	}

	public <T> T[] nextObjectArray(T[] result, final ICreator<T> creator) throws IOException, NumberFormatException {
		for(int i=0, N=result.length; i < N; i++) result[i] = nextObject(creator);

		return result;
	}

	public <T> ArrayList<T> nextGenericObjectArrayList(final int N, final ICreator<T> creator) throws IOException, NumberFormatException {
		ArrayList<T> result = new ArrayList<T>();
		for(int i=0; i < N; i++) result.add(nextObject(creator));

		return result;
	}

	public void nextTable(final int N, IArrayInitializer... arrayInitializers) throws IOException, NumberFormatException {
		for(int i=0; i < N; i++) for(IArrayInitializer initializer: arrayInitializers)
		{
			initializer.initialize(this, i);
		}
	}
}

Tree Walk

Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either

contains no nodes, or

is composed of three disjoint sets of nodes:

- a root node.

- a binary tree called its left subtree.

- a binary tree called its right subtree.

Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:

Print the root, the left subtree and right subtree (preorder).

Print the left subtree, the root and right subtree (inorder).

Print the left subtree, right subtree and the root (postorder).

Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n linen, the information of each node is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1

Output

In the 1st line, print "Preorder", and in the 2nd line print a list of node IDs obtained by the preorder tree walk.

In the 3rd line, print "Inorder", and in the 4th line print a list of node IDs obtained by the inorder tree walk.

In the 5th line, print "Postorder", and in the 6th line print a list of node IDs obtained by the postorder tree walk.

Print a space character before each node ID.

Constraints

1 ≤ n ≤ 25

Sample Input 1

9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

Sample Output 1

Preorder
0 1 2 3 4 5 6 7 8
Inorder
2 1 3 0 6 5 7 4 8
Postorder
2 3 1 6 7 5 8 4 0

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
 class Main {

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

		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		Node root = null;

		for (int i = 0; i < num; i++) {
			String element = scanner.next();
			if (!element.equals("print")) {
				int key = scanner.nextInt();
				Node node = new Node(key);
				if (root == null) {
					root = node;
					continue;
				}
				treeInsert(root, node);
			} else {
				StringBuilder stringBuilder = new StringBuilder();
				root.inorderTreeWalk(stringBuilder);
				System.out.println(stringBuilder);
				stringBuilder = new StringBuilder();
				root.preorderTreeWalk(stringBuilder);
				System.out.println(stringBuilder);
			}
		}

	}

	static void treeInsert(Node root, Node z) {
		Node y = null;
		Node x = root;
		while (x != null) {
			y = x;
			if (z.key < x.key) {
				x = x.leftChild;
			} else {
				x = x.rightChild;
			}
		}
		z.parent = y;

		if (y == null) {
			root = z;
		} else if (z.key < y.key) {
			y.leftChild = z;
		} else {
			y.rightChild = z;
		}
	}
}
 class Node {
	/** ????????????????????§??? */
	public Node parent;

	/** ???????????§??? */
	public Node rightChild;

	/** ???????????§??? */
	public Node leftChild;

	/** ?????????????????§??? */
	public int key;

	public Node(int key) {
		this.key = key;
	}

	/** ??????????????????????????? */
	public void inorderTreeWalk(StringBuilder stringBuilder) {
		if (leftChild != null) {
			leftChild.inorderTreeWalk(stringBuilder);
		}
		stringBuilder.append(" " + String.valueOf(key));
		if (rightChild != null) {
			rightChild.inorderTreeWalk(stringBuilder);
		}
	}

	/** ??????????????????????????? */
	public void preorderTreeWalk(StringBuilder stringBuilder) {
		stringBuilder.append(" " + String.valueOf(key));
		if (leftChild != null) {
			leftChild.preorderTreeWalk(stringBuilder);
		}
		if (rightChild != null) {
			rightChild.preorderTreeWalk(stringBuilder);
		}
	}
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


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

class Node {
	int key;
	Node parent, left, right;

	public Node(int key) {
		super();
		this.key = key;
	}

}

class Tree {
	Node root;

	void insert(Node z) {
		Node y = null; // parent of x
		Node x = this.root; // the root of Tree

		while (x != null) {
			y = x;
			if (z.key < x.key) {
				x = x.left;
			} else {
				x = x.right;
			}
		}
		z.parent = y;

		if (y == null) {
			this.root = z;
		} else {
			if (z.key < y.key) {
				y.left = z;
			} else {
				y.right = z;
			}
		}
	}

}

public class Main {

	static StringBuilder sb;

	public static void printPreOrder(Node node) {
		if (node == null) {
			return;
		}

		sb.append(" " + node.key);
		printPreOrder(node.left);
		printPreOrder(node.right);
	}

	public static void printInOrder(Node node) {
		if (node == null) {
			return;
		}

		printInOrder(node.left);
		sb.append(" " + node.key);
		printInOrder(node.right);
	}

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

		int m = Integer.parseInt(br.readLine());
		String[] operation;
		int key;
		Tree tree = new Tree();
		sb = new StringBuilder();

		for (int i = 0; i < m; i++) {
			operation = br.readLine().split(" ");
			if (operation[0].equals("insert")) {
				key = Integer.parseInt(operation[1]);
				tree.insert(new Node(key));
			} else {
				printInOrder(tree.root);
				sb.append("\n");
				printPreOrder(tree.root);
				System.out.println(sb.toString());
				sb.setLength(0);
			}
		}
	}
}


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

class Main {

	static int n;
	static double[] x1, y1, x2, y2;
	static double sx, sy, gx, gy;
	static ArrayList<Integer>[] g;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int q = sc.nextInt();
		while (q-- > 0) {
			double x0, y0, x1, y1, x2, y2, x3, y3;
			x0 = sc.nextDouble();
			y0 = sc.nextDouble();
			x1 = sc.nextDouble();
			y1 = sc.nextDouble();
			x2 = sc.nextDouble();
			y2 = sc.nextDouble();
			x3 = sc.nextDouble();
			y3 = sc.nextDouble();
			Point p0 = new Point(x0, y0);
			Point p1 = new Point(x1, y1);
			Point p2 = new Point(x2, y2);
			Point p3 = new Point(x3, y3);
			if (linesIntersect(p0, p1, p2, p3)) {
				System.out.println(1);
			} else {
				System.out.println(0);
			}
		}
		// ArrayList<Point> ps = new ArrayList<>();
		// n = sc.nextInt();
		// x1 = new double[n];
		// y1 = new double[n];
		// x2 = new double[n];
		// y2 = new double[n];
		// for (int i = 0; i < n; ++i) {
		// x1[i] = sc.nextDouble();
		// y1[i] = sc.nextDouble();
		// x2[i] = sc.nextDouble();
		// y2[i] = sc.nextDouble();
		// ps.add(new Point(x1[i], y1[i]));
		// ps.add(new Point(x2[i], y2[i]));
		// }
		//
		// for (int i = 0; i < n; ++i) {
		// for (int j = i + 1; j < n; ++j) {
		//
		// }
		// }

	}

	static class Point {
		double x, y;
		int id;

		public Point(double x, double y) {
			this.x = x;
			this.y = y;
		}
	}

	static boolean linesIntersect(Point s1, Point d1, Point s2, Point d2) {
		return ((crossProduct(s1, d1, s1, d2) * crossProduct(s1, d1, s1, s2)) < 0)
				&& ((crossProduct(s2, d2, s2, s1) * crossProduct(s2, d2, s2, d1) < 0));
	}

	static double crossProduct(Point s1, Point d1, Point s2, Point d2) {
		return (d1.x - s1.x) * (d2.y - s2.y) - (d1.y - s1.y) * (d2.x - s2.x);
	}

	static void tr(Object... objects) {
		System.out.println(Arrays.deepToString(objects));
	}
}

Intersection

For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise.

s1 is formed by end points p0 and p1, and
s2 is formed by end points p2 and p3.

Input

The entire input looks like:

q (the number of queries)
1st query
2nd query
...
qth query

Each query consists of integer coordinates of end points of s1 and s2 in the following format:

xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3

Output

For each query, print "1" or "0".

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

Sample Input 1

3
0 0 3 0 1 1 2 -1
0 0 3 0 3 1 3 -1
0 0 3 0 3 -2 5 0

Sample Output 1

1
1
0


import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner();
        int n=scanner.nextInt();
        int m=scanner.nextInt();
        int[] c=new int[m];
        for(int i=0;i<m;i++){
            c[i]= scanner.nextInt();
        }
        int[] dp=new int[n+1];
        for(int i=1;i<=n;i++){
            dp[i]=Integer.MAX_VALUE;
        }
        for(int i=0;i<m;i++){
            for(int j=0;j<=n;j++){
                if(j-c[i]<0)continue;
                dp[j]=Math.min(dp[j],dp[j-c[i]]+1);
            }
            //put(Arrays.toString(dp));
        }
        put(dp[n]);

    }

    public static int upper_bound(int[] a,int val){
        return upper_bound(a,0,a.length,val);
    }
    public static int upper_bound(int[] a,int l,int r,int val){
        if(r-l==1){
            if(a[l]>val) return l;
            return r;
        }
        int mid=(l+r)/2;
        if(a[mid]>val){
            return upper_bound(a,l,mid,val);
        }else{
            return upper_bound(a,mid,r,val);
        }
    }
    public static int lower_bound(int[] a,int val){
        return lower_bound(a,0,a.length,val);
    }
    public static int lower_bound(int[] a,int l,int r,int val){
        if(r-l==1){
            if(a[l]<val) return r;
            return l;
        }
        int mid=(l+r)/2;
        if(a[mid]<val){
            return lower_bound(a,mid,r,val);
        }else{
            return lower_bound(a,l,mid,val);
        }

    }

    public static int max(int a,int b){
        return Math.max(a,b);
    }
    public static long max(long a,long b){
        return Math.max(a,b);
    }
    public static int abs(int a){
        return Math.abs(a);
    }
    public static long abs(long a){
        return Math.abs(a);
    }
    public static void print(Object object){
        System.out.print(object);
    }
    public static void put(Object object) {
        System.out.println(object);
    }
    public static void put(){
        System.out.println();
    }
    public static String format(String string, Object... args) {
        return String.format(string, args);
    }
}

final class Scanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

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

Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3


import static java.lang.Math.*;

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

public class Main {

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

	static int INF = 1 << 30;
	static int MOD = 1000000007;
	static int[] mh4 = { 0, -1, 1, 0 };
	static int[] mw4 = { -1, 0, 0, 1 };
	static int[] mh8 = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] mw8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static class TaskX {

		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int n = in.nextInt(), W = in.nextInt();
			int[][] dp = new int[n+1][W+1];
			int[] v = new int[n];
			int[] w = new int[n];
			for (int i = 0; i < n; i++) {
				v[i] = in.nextInt();
				w[i] = in.nextInt();
			}

			for (int i = 0; i < n; i++) {
				for (int j = 0; j < W+1; j++) {
					if (j-w[i] >= 0) {
						dp[i+1][j] = max(max(dp[i+1][j-w[i]] + v[i], dp[i][j-w[i]] + v[i]), dp[i][j]);
					} else {
						dp[i+1][j] = dp[i][j];
					}
				}
			}

			out.println(dp[n][W]);

		}
	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

		public String nextString() {
			while (!tok.hasMoreTokens()) {
				try {
					tok = new StringTokenizer(in.readLine(), " ");
				} catch (IOException e) {
					throw new InputMismatchException();
				}
			}
			return tok.nextToken();
		}

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

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

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

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

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

		public InputReader(InputStream inputStream) {
			in = new BufferedReader(new InputStreamReader(inputStream));
			tok = new StringTokenizer("");
		}
	}

}

Knapsack Problem

You have N kinds of items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

You can select as many items as possible into a knapsack for each kind.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 1000

1 ≤ wi ≤ 1000

1 ≤ W ≤ 10000

Sample Input 1

4 8
4 2
5 2
2 1
8 3

Sample Output 1

21

Sample Input 2

2 20
5 9
4 10

Sample Output 2

10

Sample Input 3

3 9
2 1
3 1
5 2

Sample Output 3

27


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.NoSuchElementException;

public class Main {
	private static FastScanner sc = new FastScanner();

	public static void main(String[] args) {
		int N = sc.nextInt();
		long W = sc.nextLong();
		long[] v = new long[N];
		long[] w = new long[N];
		for(int i=0; i<N; i++) {
			v[i] = sc.nextLong();
			w[i] = sc.nextLong();
		}

		if(N <= 20) {
			long max = 0;
			for(int i=0; i<Math.pow(2, N); i++) {
				long vsum = 0;
				long wsum = 0;
				for(int j=0; j<N; j++) {
					if((i >> j & 1) == 1) {
						vsum += v[j];
						wsum += w[j];
					}
				}
				if(wsum <= W && vsum > max) {
					max = vsum;
				}
			}
			System.out.println(max);
		} else {
			ArrayList<Set> set1 = new ArrayList<>();
			for(int i=0; i<Math.pow(2, 20); i++) {
				long vsum = 0;
				long wsum = 0;
				for(int j=0; j<20; j++) {
					if((i >> j & 1) == 1) {
						vsum += v[j];
						wsum += w[j];
					}
				}
				set1.add(new Set(vsum, wsum, i));
			}
			ArrayList<Set> set2 = new ArrayList<>();
			for(int i=0; i<Math.pow(2, N-20); i++) {
				long vsum = 0;
				long wsum = 0;
				for(int j=0; j<N-20; j++) {
					if((i >> j & 1) == 1) {
						vsum += v[j+20];
						wsum += w[j+20];
					}
				}
				set2.add(new Set(vsum, wsum, i));
			}
			Collections.sort(set2, (a, b) -> {
				if(a.wsum > b.wsum) {
					return 1;
				} else if(a.wsum < b.wsum){
					return -1;
				} else {
					return a.id > b.id ? 1 : -1;
				}
			});
			long temp = 0;
			for(int i=0; i<set2.size(); i++) {
				if(set2.get(i).vsum > temp) {
					temp = set2.get(i).vsum;
				} else if(set2.get(i).vsum < temp) {
					set2.get(i).vsum = temp;
				}
			}
			long max = 0;
			for(int i=0; i<set1.size(); i++) {
				long wrest = W - set1.get(i).wsum;
				if(wrest < 0) continue;
				int l = 0;
				int r = set2.size() - 1;
				int m = (l + r) / 2;
				while(l <= r) {
					m = (l + r) / 2;
					if(set2.get(m).wsum > wrest) {
						r = m - 1;
					} else if(set2.get(m).wsum < wrest) {
						if(m+1 >= set2.size() || set2.get(m+1).wsum > wrest) {
							break;
						} else {
							l = m + 1;
						}
					} else {
						while(true) {
							if(m+1 >= set2.size()) break;
							if(set2.get(m+1).wsum == wrest) {
								m++;
							} else {
								break;
							}
						}
						break;
					}
				}
				if(m < 0) m = 0;
				if(m >= set2.size()) m = set2.size() - 1;
				if(set1.get(i).vsum + set2.get(m).vsum > max) {
//					System.out.println(set1.get(i).vsum + " " + set2.get(m).vsum);
					max = set1.get(i).vsum + set2.get(m).vsum;
				}
			}
			System.out.println(max);
		}
	}

	static class Set {
		int id;
		long vsum;
		long wsum;
		Set(long vsum, long wsum, int id) {
			this.vsum = vsum;
			this.wsum = wsum;
			this.id = id;
		}
	}

	static class FastScanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;
        private boolean hasNextByte() {
            if(ptr < buflen) {
                return true;
            } else {
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch(IOException e) {
                    e.printStackTrace();
                }
                if(buflen <= 0) {
                    return false;
                }
            }
            return true;
        }
        private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
        private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
        private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
        public boolean hasNext() { skipUnprintable(); return hasNextByte();}
        public String next() {
            if (!hasNext()) throw new NoSuchElementException();
            StringBuilder sb = new StringBuilder();
            int b = readByte();
            while(isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }
        public long nextLong() {
            return Long.parseLong(next());
        }
        public int nextInt(){
            return Integer.parseInt(next());
        }
        public double nextDouble(){
            return Double.parseDouble(next());
        }
    }
}

Huge Knapsack Problem

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following N lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 40

1 ≤ vi ≤ 1015

1 ≤ wi ≤ 1015

1 ≤ W ≤ 1015

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9


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

public class Main {

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

	static int INF = 1 << 30;
	static int MOD = 1000000007;
	static int[] mh4 = { 0, -1, 1, 0 };
	static int[] mw4 = { -1, 0, 0, 1 };
	static int[] mh8 = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] mw8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static class TaskX {

		int[][] sum;
		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int h = in.nextInt();
			int w = in.nextInt();

			int[][] mat = new int[h+1][w+1];
			for (int i = 0; i < h; i++) {
				for (int j = 0; j < w; j++) {
					mat[i][j] = in.nextInt();
				}
			}

			sum = new int[h+1][w+1];
			for (int i = 0; i <= h; i++) {
				for (int j = 0; j <= w; j++) {
					sum[i][j] = mat[i][j];
					if (j - 1 >= 0) sum[i][j] += sum[i][j - 1];
					if (i - 1 >= 0) sum[i][j] += sum[i - 1][j];
					if (i - 1 >= 0 && j - 1 >= 0) sum[i][j] -= sum[i - 1][j - 1];
				}
			}

			int k = Math.min(h, w)-1;
			while (k >= 0) {
				for (int i = 0; i+k < h; i++) {
					for (int j = 0; j+k < w; j++) {
						if (get(i, j, i+k, j+k) == 0) {
							out.println((k+1)*(k+1));
							return;
						}
					}
				}
				k--;
			}

			out.println(0);
		}

		int get(int x1, int y1, int x2, int y2) {

			int res = sum[x2][y2];
			if (x1 > 0) res -= sum[x1 - 1][y2];
			if (y1 > 0) res -= sum[x2][y1 - 1];
			if (x1 > 0 && y1 > 0) res += sum[x1 - 1][y1 - 1];

			return res;
		}
	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

		public String nextString() {
			while (!tok.hasMoreTokens()) {
				try {
					tok = new StringTokenizer(in.readLine(), " ");
				} catch (IOException e) {
					throw new InputMismatchException();
				}
			}
			return tok.nextToken();
		}

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

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

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

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

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

		public InputReader(InputStream inputStream) {
			in = new BufferedReader(new InputStreamReader(inputStream));
			tok = new StringTokenizer("");
		}
	}

}

Largest Square

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest square.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

4


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

import java.util.Arrays;

public class Main {
	/*
	  TLE?????§????????¨. update???O(n)??\???????????????????¢?????????????.
	  ???????????§??? AC ???????????§, Verify?????????????????£?????????.
	*/

	public static class RMQ {
		long[][] sparse_table; // query??? O(1)???????????????, k ????????¢????????????.

		public RMQ(long[] array){ // O(n log n)
			final int depth = Integer.numberOfTrailingZeros(Integer.highestOneBit(array.length));
			sparse_table = new long[depth + 1][]; sparse_table[0] = new long[array.length];
			System.arraycopy(array, 0, sparse_table[0], 0, array.length);

			for(int k = 1; k < sparse_table.length; k++){
				sparse_table[k] = new long[array.length - (1 << k) + 1];
				for(int i = 0; i + (1 << k) <= array.length; i++) { // [i, i + (1 << k))
					// [i, i + (1 << k) -> [i, i + (1 << k) / 2), [i + (1 << k) / 2, i << (k - 1))
					sparse_table[k][i] =
							Math.min(sparse_table[k-1][i], sparse_table[k-1][i + (1 << (k - 1))]);
				}
			}
		}

		public void update(int index, long v){ // index: 0-index
			//update O(n log n) ??§???????????????. SegTree??§?????????.
			sparse_table[0][index] = v;
			for(int k = 1; k < sparse_table.length; k++){
				final int begin = Math.max(0, index - (1 << k) + 1);
				final int end = Math.min(sparse_table[k].length, index + (1 << k));
				// ?????§??§ index + [-(1 << k) + 1, (1 << k)) ??????????????´??°?????????????????????
				for(int i = begin; i < end; i++){
					sparse_table[k][i] =
							Math.min(sparse_table[k - 1][i], sparse_table[k-1][i + (1 << (k - 1))]);
				}
			}
		}

		public long query(int l, int r){ // [l, r) O(log log n)
			final int k = Integer.numberOfTrailingZeros(Integer.highestOneBit(r - l));
			// k -> ???????????????????????????????????§???2?????????
			// left -> [i, i + (1 << k)), right -> [r - (1 << k)] (?????????????????§?±0)
			return Math.min(sparse_table[k][l], sparse_table[k][r - (1 << k)]);
		}
	}

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

		final int n = sc.nextInt();
		final int q = sc.nextInt();

		long[] array = new long[n];
		Arrays.fill(array, Integer.MAX_VALUE);

		RMQ rmq = new RMQ(array);
		for(int tt = 0; tt < q; tt++){
			final int op = sc.nextInt();
			final int x  = sc.nextInt();
			final int y  = sc.nextInt();

			if(op == 0){
				rmq.update(x, y);
			}else{
				System.out.println(rmq.query(x, y + 1));
			}
		}
	}

	public static class Scanner {
		private BufferedReader br;
		private StringTokenizer tok;

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

		private void getLine() {
			try {
				while (!hasNext()) {tok = new StringTokenizer(br.readLine());}
			} catch(IOException e){ /* ignore */ }
		}

		private boolean hasNext() {
			return tok != null && tok.hasMoreTokens();
		}

		public String next() {
			getLine(); return tok.nextToken();
		}

		public int nextInt(){
			return Integer.parseInt(next());
		}
		// ??????nextXXX???XXX.parseXXX()????????????????????£?????????????????§?????\

		public void close() {
			try{ br.close(); } catch (IOException e){ /*ignore*/ }
		}
	}
}

Range Minimum Query (RMQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

3 5
0 0 1
0 1 2
0 2 3
1 0 2
1 1 2

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5


import java.util.Scanner;

public class Main {
	int[] a;
	int n=1;
	public static void main(String[] args){
		Main test = new Main();
		Scanner inputScanner = new Scanner(System.in).useDelimiter("\\s");
		int n1 = inputScanner.nextInt();
		int q = inputScanner.nextInt();

		while (test.n < n1){
			test.n *= 2;
		}
	//	System.out.println(Integer.toString(test.n));
		test.a = new int[(2 * test.n)-1 ];
	//	System.out.println(test.a.length);
		for(int i=0;i<test.a.length;i++){
			test.a[i]=Integer.MAX_VALUE;
		}

		int cmd=-1;
		int arg1;
		int arg2;
		for(int j =0;j<q;j++){
			cmd = inputScanner.nextInt();
			arg1=inputScanner.nextInt();
			arg2=inputScanner.nextInt();

			if(cmd ==0)
				test.update(arg1, arg2);
			else if(cmd ==1)
				System.out.println(test.findMin(arg1, arg2));
		}
	}

	public void update(int k, int b){
		k += (n-1);
		a[k] = b;
		while(k > 0){
			k = (k-1)/2;
			a[k] = Integer.min(a[(k*2)+1], a[(k*2)+2]);
		}
	}

	public int findMin(int b, int c){

		return query(b,c+1,0,0,n);
	}

	public int query(int b, int c, int k, int l, int r){
		if (r <= b || c <= l)
			return Integer.MAX_VALUE;
		if((b<=l && r<=c))
			return a[k];

		int o1 = query(b,c,(k*2)+1,l,(l+r)/2);
		int o2 = query(b,c,(k*2)+2,(l+r)/2,r);
		return Integer.min(o1, o2);
	}
}


import java.util.*;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

class Point {
    int id;
    long x;
    long y;

    Point(int id, long x, long y) {
        this.id = id;
        this.x = x;
        this.y = y;
    }
}

class KDTree {
    private static final int K = 2;

    KDNode root;
    private Point[] points;
    private List<Point> answer;

    KDTree(Point[] points) {
        this.points = points;
        this.root = build(0, points.length, 0);
    }

    private KDNode build(int l, int r, int depth) {
        if (l >= r) return null;

        int mid = (l + r) / 2;
        if (depth % K == 0) {
            Arrays.sort(points, l, r, xComparator);
        } else if (depth % K == 1) {
            Arrays.sort(points, l, r, yComparator);
        } else {
            throw new RuntimeException();
        }

        KDNode node = new KDNode();

        node.location = mid;
        node.l = build(l, mid, depth + 1);
        node.r = build(mid + 1, r, depth + 1);

        return node;
    }

    List<Point> find(Point p1, Point p2) {
        answer = new LinkedList<>();
        long sx = Math.min(p1.x, p2.x);
        long sy = Math.min(p1.y, p2.y);
        long tx = Math.max(p1.x, p2.x);
        long ty = Math.max(p1.y, p2.y);
        find(root, sx, tx, sy, ty, 0);
        return answer;
    }

    private void find(KDNode v, long sx, long tx, long sy, long ty, int depth) {
        long x = points[v.location].x;
        long y = points[v.location].y;

        if (sx <= x && x <= tx && sy <= y && y <= ty) {
            answer.add(points[v.location]);
        }

        if (depth % K == 0) {
            if (v.l != null && sx <= x) find(v.l, sx, tx, sy, ty, depth + 1);
            if (v.r != null && x <= tx) find(v.r, sx, tx, sy, ty, depth + 1);
        } else if (depth % K == 1) {
            if (v.l != null && sy <= y) find(v.l, sx, tx, sy, ty, depth + 1);
            if (v.r != null && y <= ty) find(v.r, sx, tx, sy, ty, depth + 1);
        } else {
            throw new RuntimeException();
        }
    }

    private Comparator<Point> xComparator = new Comparator<Point>() {
        @Override
        public int compare(Point p1, Point p2) {
            return (int) Math.signum(p1.x - p2.x);
        }
    };

    private Comparator<Point> yComparator = new Comparator<Point>() {
        @Override
        public int compare(Point p1, Point p2) {
            return (int) Math.signum(p1.y - p2.y);
        }
    };

    class KDNode {
        int location;
        KDNode l, r;
    }
}

public class Main {
    public static void main(String[] args) {
        new Solver().solve(new Scanner(System.in));
//        new Solver().solve(new Scanner(ex));
    }

    private static final String ex = "6\n" +
            "2 1\n" +
            "2 2\n" +
            "4 2\n" +
            "6 2\n" +
            "3 3\n" +
            "5 4\n" +
            "2\n" +
            "2 4 0 4\n" +
            "4 10 2 5";
}

class Solver {
    void solve(Scanner scanner) {
        int n = Integer.parseInt(scanner.nextLine());
        Point[] points = new Point[n];
        for (int i = 0; i < n; i ++) {
            long[] split = splitLong(scanner.nextLine());
            points[i] = new Point(i, split[0], split[1]);
        }
        KDTree tree = new KDTree(points);
        int q = Integer.parseInt(scanner.nextLine());
        for (int i = 0; i < q; i ++) {
            long[] split = splitLong(scanner.nextLine());
            long sx = split[0];
            long tx = split[1];
            long sy = split[2];
            long ty = split[3];
            List<Point> result = tree.find(new Point(-1, sx, sy), new Point(-1, tx, ty));
            result.stream().mapToInt(x -> x.id).sorted().forEach(System.out::println);
            System.out.println();
        }
    }

    private int[] splitInt(String s) {
        String[] split = s.split(" ");
        int[] splitInt = new int[split.length];
        for (int i = 0; i < split.length; i ++) {
            splitInt[i] = Integer.parseInt(split[i]);
        }
        return splitInt;
    }

    private long[] splitLong(String s) {
        String[] split = s.split(" ");
        long[] splitLong = new long[split.length];
        for (int i = 0; i < split.length; i ++) {
            splitLong[i] = Long.parseLong(split[i]);
        }
        return splitLong;
    }
}

Range Search (kD Tree)

The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.

For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.

Input

n
x0 y0
x1 y1
:
xn-1 yn-1
q
sx0 tx0 sy0 ty0
sx1 tx1 sy1 ty1
:
sxq-1 txq-1 syq-1 tyq-1

The first integer n is the number of points. In the following n lines, the coordinate of the i-th point is given by two integers xi and yi.

The next integer q is the number of queries. In the following q lines, each query is given by four integers,
sxi,
txi,
syi,
tyi.

Output

For each query, report IDs of points such that
sxi ≤ x ≤ txi and
syi ≤ y ≤ tyi.
The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query.

Constraints

0 ≤ n ≤ 500,000

0 ≤ q ≤ 20,000

-1,000,000,000 ≤ x, y, sx, tx, sy, ty ≤ 1,000,000,000

sx ≤ tx

sy ≤ ty

For each query, the number of points which are within the range is less than or equal to 100.

Sample Input 1

6
2 1
2 2
4 2
6 2
3 3
5 4
2
2 4 0 4
4 10 2 5

Sample Output 1

0
1
2
4

2
3
5


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

public class Main {

    public static void main(String[] argv) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int v = Integer.parseInt(str[0]);
        int e = Integer.parseInt(str[1]);

        long[][] map = new long[v][v];
        for(long[] obj: map)
            Arrays.fill(obj, Long.MAX_VALUE/2);
        for(int i=0; i<v; i++)
            map[i][i] = 0;

        for(int j=0; j<e; j++){
            str = br.readLine().split(" ");
            int from = Integer.parseInt(str[0]);
            int to = Integer.parseInt(str[1]);
            int cost = Integer.parseInt(str[2]);

            map[from][to] = cost;
        }

        for(int i=0; i<v; i++) {
            for (int j = 0; j < v; j++) {
                for (int k = 0; k < v; k++) {
                    if (map[i][j] > map[i][k] + map[k][j])
                        map[i][j] = map[i][k] + map[k][j];
                }
            }
        }

        for (int i=0; i<v; i++) {
            if (map[i][i] < 0){
                System.out.println("NEGATIVE CYCLE");
                System.exit(0);
            }
        }

        for(int i=0; i<v; i++) {

            String[] out = new String[v];
            for (int j = 0; j < v; j++) {
                if (map[i][j] == Long.MAX_VALUE/2) {
                    out[j] = "INF";
                } else {
                    out[j] = String.valueOf(map[i][j]);
                }
            }
            System.out.println(String.join(" ", out));
        }

    }
}

All Pairs Shortest Path

Input

An edge-weighted graph G (V, E).

|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print

NEGATIVE CYCLE

in a line.

Otherwise, print

D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1

The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.

Constraints

1 ≤ |V| ≤ 100

0 ≤ |E| ≤ 9900

-2 × 107 ≤ di ≤ 2 × 107

There are no parallel edges

There are no self-loops

Sample Input 1

4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7

Sample Output 1

0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0

Sample Input 2

4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7

Sample Output 2

0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0

Sample Input 3

4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7

Sample Output 3

NEGATIVE CYCLE


import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] ve = scanner.nextLine().split(" ", 2);
        int v = Integer.parseInt(ve[0]);
        int e = Integer.parseInt(ve[1]);

        Map<Integer, List<Integer>> vEdges = new HashMap<>();

        for (int i = 0; i < e; i++) {
            String[] st = scanner.nextLine().split(" ", 2);
            int s = Integer.parseInt(st[0]);
            int t = Integer.parseInt(st[1]);

            List<Integer> edges = vEdges.get(s);
            if (edges == null) {
                edges = new ArrayList<>();
                vEdges.put(s, edges);
            }
            edges.add(t);
        }

        Set<Integer> visited = new HashSet<>();
        List<Integer> sorted = new ArrayList<>();
        for (int i = 0; i < v; i++) {
            visit(visited, sorted, vEdges, i, 0);
        }

        for (Integer vertex : sorted) {
            System.out.println(vertex);
        }
    }

    private static void visit(Set<Integer> visited, List<Integer> sorted, Map<Integer, List<Integer>> vEdges, int vertex, int depth) {
        if (visited.contains(vertex)) return;
        visited.add(vertex);

        if (vEdges.containsKey(vertex)) {
            for (Integer edge : vEdges.get(vertex)) {
                visit(visited, sorted, vEdges, edge, depth + 1);
            }
        }
        sorted.add(0, vertex);
    }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Topological Sort

A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obtain the proper sequence of all the tasks by a topological sort.

Given a DAG $G$, print the order of vertices after the topological sort.

Input

A directed graph $G$ is given in the following format:

$|V|\;|E|$

$s_0 \; t_0$

$s_1 \; t_1$

:

$s_{|E|-1} \; t_{|E|-1}$

$|V|$ is the number of vertices and $|E|$ is the number of edges in the graph. The graph vertices are named with the numbers $0, 1,..., |V|-1$ respectively.

$s_i$ and $t_i$ represent source and target nodes of $i$-th edge (directed).

Output

Print the vertices numbers in order. Print a number in a line.

If there are multiple possible solutions, print any one of them (the solution is judged by a special validator).

Constraints

$1 \leq |V| \leq 10,000$

$0 \leq |E| \leq 100,000$

There are no parallel edges in $G$

There are no self loops in $G$

Sample Input

6 6
0 1
1 2
3 1
3 4
4 5
5 2

Sample Output

0
3
1
4
5
2


import java.util.Scanner;

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

        double a = sc.nextDouble();
        double b = sc.nextDouble();
        double angle = Math.toRadians(sc.nextDouble());
        double c = Math.sqrt(a*a + b*b - 2*a*b*Math.cos(angle));
        double L = a + b + c;
        double S = (a*b * Math.sin(angle))/2;
        double h = 2 * S / a;
        System.out.println(S);
        System.out.println(L);
        System.out.println(h);
    }
}

Triangle

For given two sides of a triangle a and b and the angle C between them, calculate the following properties:

S: Area of the triangle

L: The length of the circumference of the triangle

h: The height of the triangle with side a as a bottom edge

Input

The length of a, the length of b and the angle C are given in integers.

Output

Print S, L and h in a line respectively. The output should not contain an absolute error greater than 10-4.

Sample Input

4 3 90

Sample Output

6.00000000
12.00000000
3.00000000


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);

        while(true){
            int count = scn.nextInt();

            if(count == 0) break;

            int [] array;
            array = new int[count];

            int sum = 0;
            Double ave = 0.0;
            Double ans = 0.0;
            Double answer = 0.0;

            for(int i = 0; i < count; i++){
                array[i] = scn.nextInt();
                sum += array[i];
            }

            ave = Double.valueOf(sum) / Double.valueOf(count);

            for(int i = 0; i < count; i++){
                ans += (array[i] - ave) * (array[i] - ave);
            }
            ans /= count;
            answer = Math.sqrt(ans);

            System.out.println(String.format("%.8f", answer));

        }
    }
}

Standard Deviation

You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.

The variance α2 is defined by

α2 = (∑ni=1(si - m)2)/n

where m is an average of si.

The standard deviation of the scores is the square root of their variance.

Input

The input consists of multiple datasets. Each dataset is given in the following format:

n
s1 s2 ... sn

The input ends with single zero for n.

Output

For each dataset, print the standard deviation in a line. The output should not contain an absolute error greater than 10-4.

Constraints

n ≤ 1000

0 ≤ si ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000