import java.util.Scanner;

class Card {
  char suit;
  int value;
}

public class Main {
  static void bubbleSort(Card[] a, int n) {
    boolean flag = true;
    for (int i = 0; flag; i ++) {
      flag = false;
      for (int j = n - 1; j >= i + 1; j--) {
        if (a[j].value < a[j-1].value) {
          Card t = a[j];
          a[j] = a[j-1];
          a[j-1] = t;
          flag = true;
        }
      }
    }
  }

  static void selectionSort(Card[] a, int n) {
    for (int i = 0; i < n; i++) {
      int minj = i;
      for (int j = i; j < n; j++)
        if (a[j].value < a[minj].value)
          minj = j;
      Card t = a[i];
      a[i] = a[minj];
      a[minj] = t;
    }
  }

  static boolean isStable(Card[] c1, Card[] c2, int n) {
    for (int i = 0; i < n; i++)
      if (c1[i].suit != c2[i].suit) return false;
    return true;
  }

  static void print(Card[] a, int n) {
    for (int i = 0; i < n; i++) {
      System.out.print(a[i].suit);
      System.out.print(a[i].value);
      if (i != n - 1) System.out.print(' ');
      else System.out.println();
    }
  }

  public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    int n = stdIn.nextInt();
    Card[] c1 = new Card[n];
    Card[] c2 = new Card[n];
    String[] s = new String[n];
    for (int i = 0; i < n; i++) {
      c1[i] = new Card();
      c2[i] = new Card();
      s[i] = stdIn.next();
      c1[i].suit = s[i].charAt(0);
      c1[i].value = Integer.parseInt(s[i].substring(1,2));
      c2[i] = c1[i];
    }
  bubbleSort(c1, n);
  selectionSort(c2, n);
  print(c1, n);
  System.out.println("Stable");
  print(c2, n);
  if (isStable(c1, c2, n)) System.out.println("Stable");
  else System.out.println("Not stable");
  }
}


import java.util.*;

class Main{
    public static void main(String[] args){
    Queue<String> queue = new ArrayDeque<String>();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt(); //処理する数
    int q = sc.nextInt(); //クオンタム
    int sum = 0;          //処理した数
    int sumTime = 0;      //合計処理時間
    for(int i = 0; i < 2*n; i++){
        String x = sc.next();
        queue.add(x);
    }
    /*処理部分*/
    while(sum != n){
        String name = queue.poll();
        int time = Integer.parseInt(queue.poll());
        if(time > q){
            sumTime += q;
            time -= q;
            queue.add(name);
            queue.add(String.valueOf(time));  //intをInteger経由でStringに変換している
        }
        else{
            sumTime += time;
            sum++;
            System.out.println(name +" "+sumTime);
        }
    }

    }
}

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

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C

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.Scanner;
import java.util.ArrayDeque;
import java.util.Queue;

class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        Queue<Integer> queue = new ArrayDeque<>();

        int n = sc.nextInt();
        int q = sc.nextInt();
        String name[] = new String[n];
        int time[] = new int[n];
        for(int i = 0; i < n; i++){
            name[i] = sc.next();
            time[i] = sc.nextInt();
            queue.add(i);
        }

        int x = 0;
        while(!queue.isEmpty()){
            int y = queue.poll();
            if(time[y] <= q){
                x += time[y];
                System.out.println(name[y]+" "+x);
            }else{
                x += q;
                time[y] -= q;
                queue.add(y);
            }
        }
    }
}


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

class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        String[] line = sc.nextLine().split(" ");
        int[] data =new int[n];
        for(int i=0; i < n; i++){
            data[i] = Integer.parseInt(line[i]);
        }

        int q = Integer.parseInt(sc.nextLine());
        String[] line2 = sc.nextLine().split(" ");
        int[] searcher = new int[q];
        for(int i=0; i < q; i++){
            searcher[i] = Integer.parseInt(line2[i]);
        }

        int result = 0;
        for(int i = 0; i < q; i++){
            for(int j = 0; j < n; j++){
                if(searcher[i] == data[j]){
                    result++;
                    break;
                }
            }
        }
        System.out.println(result);

    }
    static void bubble(int[] arr, int n){

    }
    static void selection(int[] arr, int n){

    }
    static void insertionSort(int[] arr, int n, int g,int count){
        for(int i = g; i < n; i++){
            int v = arr[i];
            int j = i - g;
            while(j >= 0 && arr[j] > arr[i]){
                arr[i] = arr[j];
                j-=g;
                count++;
            }
            arr[j + g] = v;
        }
    }
    static void shellsort(int[] arr, int n){

        for(int i = 1; ; ){
            if(i > n){
                break;
            }

            i = (i * 3) + 1;
        }
    }
}
class Struct{
    String name;
    int time;
    public Struct(String n, int t){
        name = n;
        time = t;
    }
}

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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {

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

	   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	   int n = Integer.parseInt( br.readLine() );
	   String[] string =  br.readLine().split(" ");
       int[] S = new int[n];

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

    	   S[i] = Integer.parseInt( string[i] );

       }

       int q = Integer.parseInt( br.readLine() );
	   String[] stringq =  br.readLine().split(" ");
       int[] T = new int[q];

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

    	   T[i] = Integer.parseInt( stringq[i] );

       }

       int answer = 0;

       for(int i = 0; i < q ; i++ ){
    	   for(int j = 0; j < n ;  j++ ){
    		   if( S[j] == T[i]  ){
    			   answer++;
    			   break;
    		   }
    	   }

       }

     System.out.println(answer);

   }

}

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 {
    static boolean binary_search (int x, int[] data) {
        int left = 0, right = data.length;
        while (true) {
            int mid = (left + right) / 2;

            if (left > right) return false;

            if (data[mid] == x) {
                return true;
            } else if (data[mid] < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }

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

        int n = scanner.nextInt();

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

        int q = scanner.nextInt();

        int cnt = 0;
        for (int i = 0; i < q; ++i) {
            int t = scanner.nextInt();
            if (binary_search(t, s)) ++cnt;
        }

        System.out.println(cnt);
    }
}


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

public class Main
{
	public static int A[] = new int[20];
	public static boolean rec(int s, int n, int now)
	{
		if(n == -1)
		{
			if(now == s)
			{
				return true;
			}
			return false;
		}
		return rec(s, n - 1, now + A[n]) | rec(s, n - 1, now);
	}
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n, q, m[] = new int[200];
		n = sc.nextInt();
		for(int i = 0; i < n; i++)
		{
			A[i] = sc.nextInt();
		}
		q = sc.nextInt();
		for(int i = 0; i < q; i++)
		{
			m[i] = sc.nextInt();
		}
		for(int i = 0; i < q; i++)
		{
			if(rec(m[i], n - 1, 0))
			{
				System.out.println("yes");
			}
			else
			{
				System.out.println("no");
			}
		}
		sc.close();
	}
}

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

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 (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


import java.util.Scanner;

public class Main {
static int n;
static int S[]=new int[500001];
static int count=0;

  public static void merge(int left,int mid,int right){

	  int i,j;
	  mid=(left+right)/2;

	  int n1=mid-left;
	  int n2=right-mid;
	 int infty=Integer.MAX_VALUE;

	  int R[]=new int[n1+2];
	  int L[]=new int[n2+2];

	  for(i=0;i<n1;i++){
		  L[i]=S[left+i];
	  }
	  for(i=0;i<n2;i++){
		  R[i]=S[mid+i];
	  }

	  L[n1]=infty;
	  R[n2]=infty;
	i=0;
	j=0;

	for(int k=left;k<right;k++){
		count++;
		if(L[i]<=R[j]){
			S[k]=L[i];
			i++;
		}
		else{
			S[k]=R[j];
			j++;
		}

	}

  }

  public static void mergesort(int left,int right){
	  if(left+1<right){
		  int mid=(left+right)/2;
		  mergesort(left,mid);
		  mergesort(mid,right);
		  merge(left,mid,right);
	  }
  }

	public static void main(String[] args) {
		int i;
	    int left1,right1;

		 Scanner sc=new Scanner(System.in);
		 n=Integer.parseInt(sc.next());

		  for(i=0;i<n;i++){
		  	  S[i]=Integer.parseInt(sc.next());
		  }
		  left1=0;
		  right1=n;

		  mergesort(left1,right1);

			  for(i=0;i<n;i++){
					System.out.print(S[i]);
					if(i==n-1){System.out.println("");
					}
			  else{
				  System.out.print(" ");
			  }
			  }
			  System.out.println(count);
  }
}

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.util.Scanner;

class Main {
	static int count = 0;
	public static void main (String[] args) {
		Scanner scan = new Scanner (System.in);
		int n = scan.nextInt();
		int[] data = new int[n];

		for (int i = 0; i < n; i++) {
			data[i] = scan.nextInt();
		}
		scan.close();

		Main obj = new Main();
		obj.MergeSort (data, 0, n);
		printArray (data);
		System.out.println(count);
	}

	void MergeSort (int[] data, int left, int right) {

		if (left + 1 < right) {
			int mid = (left + right) / 2;

			MergeSort(data, left, mid);
			MergeSort(data, mid, right);

			Merge(data, left, mid, right);

		}
	}

	void Merge (int[] data, int left, int mid, int right) {
		int n1 = mid - left;
		int n2 = right - mid;
		final int INFTY = 1000000000;

		int[] L = new int[n1 + 1];
		int[] R = new int[n2 + 1];

		for (int i = 0; i < n1; i++) {
			L[i] = data[left + i];
		}
		for (int i = 0; i < n2; i++) {
			R[i] = data[mid + i];
		}

		L[n1] = INFTY;
		R[n2] = INFTY;

		int i = 0, j = 0;
		int k = left;

		while (true) {

			if (i == n1 && j == n2) break;

			if (L[i] <= R[j]) {
				data[k] = L[i];
				i++;
			} else {
				data[k] = R[j];
				j++;
			}
			k++;
			count++;
		}

	}

	static void printArray (int[] data) {
		int n = data.length;
		for (int i = 0; i < n; i++) {
			if ( i != n - 1) System.out.print(data[i] + " ");
			else System.out.println(data[i]);
		}
	}
}


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

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

        Scanner inp = new Scanner(System.in);
        total = inp.nextInt();

        int[] a = new int[total];

        for (int k = 0; k < total; k++) {
            a[k] = inp.nextInt();
        }

        countingSort(a, new int[total], 2000000);
    }

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

        for (int j = 0; j < a.length; j++) {
            c[a[j]]++;
        }

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

        for (int j = a.length-1; j >= 0; j--) {
            b[c[a[j]]-1] = a[j];
            c[a[j]]--;
        }

        int place = 0;
        for(int item : b) {
            if (place != 0) {
                System.out.print(" ");

            }

            System.out.print(item);
            place++;
        }

        System.out.print("\n");

    }
}

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.*;

public class Main{

	static int count = 0;

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		StringBuffer sb = new StringBuffer();
		int max = 0;
		int[] A = new int[n];
		int[] B = new int[n];
		String[] in = br.readLine().split(" ");
		for(int i = 0; i < n; i++){
			A[i] = Integer.parseInt(in[i]);
			max = Math.max(max, A[i]);
		}

		countingSort(A, B, max);
		sb.append(B[0]);
		for(int i = 1; i < n; i++)
			sb.append(" ").append(B[i]);
		String out = sb.toString();
		System.out.printf("%s\n", out);
	}

	private static void countingSort(int[] a, int[] b, int max){ // ?¨???°?????????
		int[] C = new int[max+1];

		for(int j = 0; j < a.length; j++){
			C[a[j]]++;
		}

		for(int i = 1; i <= max; i++){
			C[i] = C[i] + C[i-1]; // ?¨???°???
		}

		for(int j = a.length-1; j >= 0; j--){
			b[C[a[j]]-1] = a[j]; // ?¨???°??????????´???°??¨????????????????????????0??????k-1?????§
			C[a[j]]--; // ?????£????????§?¨???°????????????
		}
	}
}


import java.util.Scanner;

class Main {
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		int  num = scanner.nextInt();//要素数
		int array[] = new int[num];
		int max = 0;
		//実行処理
		CountingSort(array, num, max,scanner);
		//後処理
		scanner.close();
	}

	public static void CountingSort(int[] array, int num, int max, Scanner scanner){
		int[] count = new int[10000];
		int[] sort = new int[num];
		//配列作成同時にカウント
		for(int i = 0; i < num; i ++ ){
			array[i] = scanner.nextInt();
			count[ array[i] ] ++;
			//比較して更新
			max = Math.max(max, array[i]);
		}
		//カウントの位置
		for(int i = 1; i <= max; i ++ ){
			count[i] += count[i - 1];
		}
		//ソート処理
		for(int i = num - 1; i >= 0; i -- ){
				count[array[i]] --;
				sort[count[array[i]]] = array[i];

		}
		//出力
		for(int i = 0; i < num; i ++ ){
			System.out.print(sort[i]);
			if( i == num - 1) {
			System.out.print("\n");
			}else {
				System.out.print(" ");
			}
		}
	}
}


import java.util.*;
public class Main{
	static int[] A =new int[100000];
	static int n;
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		for(int i=0;i<n;i++){
			A[i]=sc.nextInt();
		}
		/*
		for(int i=0;i<n;i++){
			System.out.print(A[i] +" ");
		}
		*/

		int q = partition(0, n-1);
		for(int i = 0;i<n;i++){
			if(i != q){
				System.out.print(A[i] + " ");
			}else{
				System.out.print("[" + A[i] + "] ");
			}
		}
		System.out.println();

		return;
	}

	public static int partition(int p, int r){
		int x, i, j, t;
		x= A[r];
		i = p - 1;
		for(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.IOException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws NumberFormatException,
            IOException {
        new Main().run();
    }

    private void run() throws NumberFormatException, IOException {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++) {
            nodes[i] = new Node();
        }
        for (int i = 0; i < n; i++) {
            int v = scanner.nextInt();
            int left = scanner.nextInt();
            int right = scanner.nextInt();
            nodes[v].left = left;
            nodes[v].right = right;
            if (left != -1)
                nodes[left].p = v;
            if (right != -1)
                nodes[right].p = v;
        }

        int root = 0;
        for (int i = 0; i < n; i++) {
            if (nodes[i].p == -1) {
                root = i;
            }
        }
        System.out.println("Preorder");
        preParse(root, nodes);
        System.out.println();
        System.out.println("Inorder");
        inParse(root, nodes);
        System.out.println();
        System.out.println("Postorder");
        postParse(root, nodes);
        System.out.println();
    }

    private void postParse(int id, Node[] nodes) {
        if (id == -1) //
            return;
        postParse(nodes[id].left, nodes);
        postParse(nodes[id].right, nodes);
        System.out.print(" " + id);
    }

    private void inParse(int id, Node[] nodes) {
        if (id == -1)
            return;
        inParse(nodes[id].left, nodes);
        System.out.print(" " + id);
        inParse(nodes[id].right, nodes);
    }

    private void preParse(int id, Node[] nodes) {
        if (id == -1)
            return;
        System.out.print(" " + id);
        preParse(nodes[id].left, nodes);
        preParse(nodes[id].right, nodes);
    }

    class Node {
        int p = -1, left, right;
    }
}

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.util.Scanner;

public class Main {

	public static final int BIG_NUM = 2000000000;
	public static final int MOD = 1000000007;
	public static Node[] nodes;
	public static StringBuilder ans;

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int V = sc.nextInt();
		nodes = new Node[V];
		int[] in_num = new int[V];

		for(int i = 0; i < V; i++){
			in_num[i] = 0;
		}

		int node_id,left_child,right_child;

		for(int loop = 0; loop < V; loop++){

			node_id = sc.nextInt();
			left_child = sc.nextInt();
			right_child = sc.nextInt();

			nodes[node_id] = new Node(left_child,right_child);

			if(left_child != -1){
				in_num[left_child]++;
			}
			if(right_child != -1){
				in_num[right_child]++;
			}
		}

		int root = -1;
		for(int i = 0; i < V; i++){
			if(in_num[i] == 0){
				root = i;
				break;
			}
		}

		ans = new StringBuilder();

		ans.append("Preorder\n");
		Preorder(root);
		ans.append("\nInorder\n");
		Inorder(root);
		ans.append("\nPostorder\n");
		Postorder(root);
		ans.append("\n");

		System.out.print(ans.toString());
	}

	public static void Preorder(int node_id){

		ans.append(" ").append(Integer.toString(node_id));

		if(nodes[node_id].left_child != -1){
			Preorder(nodes[node_id].left_child);
		}
		if(nodes[node_id].right_child != -1){
			Preorder(nodes[node_id].right_child);
		}
	}

	public static void Inorder(int node_id){

		if(nodes[node_id].left_child != -1){
			Inorder(nodes[node_id].left_child);
		}
		ans.append(" ").append(Integer.toString(node_id));

		if(nodes[node_id].right_child != -1){
			Inorder(nodes[node_id].right_child);
		}
	}

	public static void Postorder(int node_id){

		if(nodes[node_id].left_child != -1){
			Postorder(nodes[node_id].left_child);
		}
		if(nodes[node_id].right_child != -1){
			Postorder(nodes[node_id].right_child);
		}
		ans.append(" ").append(Integer.toString(node_id));
	}

}

class Node{

	public int left_child;
	public int right_child;

	Node(int arg_left_child,int arg_right_child){
		left_child = arg_left_child;
		right_child = arg_right_child;
	}
}


import java.util.*;
public class Main {
    private static int cnt = 0;
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        int n  = sc.nextInt();
        int [] pt = new int[n];
        int [] it = new int[n];
        for(int i=0;i<n;i++) pt[i] = sc.nextInt();
        for(int i=0;i<n;i++) it[i] = sc.nextInt();
        reconstruction(0,n,0,pt,it);
        System.out.println();
    }
    public static int getindex(int [] L,int  value){
        for(int i=0;i<L.length;i++) if(L[i] == value) return i;
        return -1;
    }
    public static int  reconstruction(int l,int r,int pre_id,int [] pt,int [] it){
        if(l<r){
            int next_value = pt[pre_id++];
            int it_id = getindex(it,next_value);
            pre_id = reconstruction(l,it_id,pre_id,pt,it);
            pre_id = reconstruction(it_id+1,r,pre_id,pt,it);
            if(cnt==pt.length-1) System.out.print(next_value);
            else{
                System.out.print(next_value+" ");
                cnt++;
            }
        }
        return pre_id;
    }
}

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

Reconstruction of a Tree

Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.

Input

In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.

In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.

In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.

Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.

Output

Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.

Constraints

$1 \leq n \leq 40$

Sample Input 1

5
1 2 3 4 5
3 2 4 1 5

Sample Output 1

3 4 2 5 1

Sample Input 2

4
1 2 3 4
1 2 3 4

Sample Output 2

4 3 2 1


import java.util.Scanner;

/**
 * Created by zhangrunfeng on 2/18/20
 */
public class Main {

    private int N;
    private Node root;

    class Node {
        long val;
        Node left;
        Node right;

        public Node (long val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }

    private void inOrder(Node root, StringBuilder sb) {
        if (root == null) return;

        if (root.left != null) {
            inOrder(root.left, sb);
            sb.append(" ");
        }

        sb.append(root.val);

        if (root.right != null) {
            sb.append(" ");
            inOrder(root.right, sb);
        }
    }

    private void preOrder(Node root, StringBuilder sb) {
        if (root == null) return;

        sb.append(root.val);
        if (root.left != null) {
            sb.append(" ");
            preOrder(root.left, sb);
        }
        if (root.right != null) {
            sb.append(" ");
            preOrder(root.right, sb);
        }
    }

    public Main(Scanner sc) {
        N = sc.nextInt();
        for (int i = 0; i < N; i++) {
            String str = sc.next();
            if (str.equals("insert")) {
                long val = sc.nextLong();
                Node currNode = new Node(val);
                if (root == null) {
                    root = currNode;
                } else {
                    Node tmp = root;
                    while (true) {
                        if (currNode.val < tmp.val) {
                            if (tmp.left != null) {
                                tmp = tmp.left;
                            } else {
                                tmp.left = currNode;
                                break;
                            }
                        } else {
                            if (tmp.right != null) {
                                tmp = tmp.right;
                            } else {
                                tmp.right = currNode;
                                break;
                            }
                        }
                    }
                }
            } else if (str.equals("print")) {
                StringBuilder sb = new StringBuilder();
                inOrder(root, sb);
                System.out.println(" " + sb.toString());
                sb.setLength(0);
                preOrder(root, sb);
                System.out.println(" " + sb.toString());
            }
        }
    }

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

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.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Node[] heap = new Node[n + 1];
		heap[0] = new Node();
		for (int i = 1; i < n + 1; i++) {
			heap[i] = new Node();
			heap[i].id = i;
			heap[i].key = sc.nextInt();
		}

		buildMaxHeap(heap, n);
		for(int i = 1;i < n+1;i++){
			System.out.print(" "+heap[i].key);
		}
		System.out.println();
	}

	static void maxHeapify(Node A[], int i, int n) {
		int l = 2 * i;
		int r = 2 * i + 1;
		int max = i;
		//System.out.println(l+" "+r);
		if (l <= n && A[l].key > A[max].key)max = l;
		if (r <= n && A[r].key > A[max].key)max = r;
		if (max != i) {
			int temp = A[i].key;
			A[i].key = A[max].key;
			A[max].key = temp;
			maxHeapify(A, max, n);
		}

	}

	static void buildMaxHeap(Node A[], int n){
		for(int i = n/2;i > 0;i--){
			maxHeapify(A, i, n);
		}
	}
}

class Node {
	int id;
	int key;
	int p;
	int l;
	int r;

	Node() {
		id = Integer.MIN_VALUE;
		key = Integer.MIN_VALUE;
		p = Integer.MIN_VALUE;
		l = Integer.MIN_VALUE;
		r = Integer.MIN_VALUE;
	}
}

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

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

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


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

public class Main {

	class P {
		double x, y;

		P(double x_, double y_) {
			x = x_;
			y = y_;
		}

		P add(P p) {
			return new P(x + p.x, y + p.y);
		}

		P sub(P p) {
			return new P(x - p.x, y - p.y);
		}

		P mul(double v) {
			return new P(x * v, y * v);
		}

		P div(double v) {
			return new P(x / v, y / v);
		}

		double dot(P p) {
			return x * p.x + y * p.y;
		}

		double det(P p) {
			return x * p.y - y * p.x;
		}

		double abs2() {
			return x * x + y * y;
		}

		double abs() {
			return Math.sqrt(abs2());
		}

		P norm() {
			return div(abs());
		}

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

		P proj(P src, P dst) {
			P p_sd = dst.sub(src).norm();
			return src.add(p_sd.mul(sub(src).dot(p_sd)));
		}

		P reflect(P src, P dst) {
			P middle = proj(src, dst);
			return add(middle.sub(this).mul(2));
		}

		public String toString() {
			return String.format("%f %f", x, y);
		}
	}

	P isLL(P p1, P p2, P q1, P q2) {
		double d = p2.sub(p1).det(q1.sub(q2));
		if (Math.abs(d) < 1e-10)
			return null;
		return p1.add(p2.sub(p1).mul(q1.sub(q2).det(p1.sub(q2)) / d));
	}

	void run() {
		Scanner sc = new Scanner(System.in);
		int q = sc.nextInt();
		while (q-- > 0) {
			P p1 = new P(sc.nextDouble(), sc.nextDouble());
			P p2 = new P(sc.nextDouble(), sc.nextDouble());
			P q1 = new P(sc.nextDouble(), sc.nextDouble());
			P q2 = new P(sc.nextDouble(), sc.nextDouble());

			P x = isLL(p1, p2, q1, q2);
			System.out.println(String.format("%.20f %.20f", x.x, x.y));
		}
	}

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

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

}

Cross Point

For given two segments s1 and s2, print the coordinate of the cross point of them.

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 the coordinate of the cross point. The output values should be in a decimal fraction with an error less than 0.00000001.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

The given segments have a cross point and are not in parallel.

Sample Input

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

Sample Output

1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000


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

public class Main {
	static final long MOD = 1000000007;
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int n = sc.nextInt();
		int k = sc.nextInt();
		long[][] dp = new long[n + 1][k + 1];
		for (int i = 0; i <= k; i++) {
			dp[0][i] = 1;
		}
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= k; j++) {
				if (i - j >= 0) {
					dp[i][j] = dp[i][j - 1] + dp[i - j][j];
					dp[i][j] %= MOD;
				} else {
					dp[i][j] = dp[i][j - 1];
				}
			}
		}
		System.out.println(dp[n][k]);
	}
}

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

Balls and Boxes 10

Balls

Boxes

Any way

At most one ball

At least one ball

Distinguishable

Distinguishable

1

2

3

Indistinguishable

Distinguishable

4

5

6

Distinguishable

Indistinguishable

7

8

9

Indistinguishable

Indistinguishable

10

11

12

Problem

You have $n$ balls and $k$ boxes. You want to put these balls into the boxes.

Find the number of ways to put the balls under the following conditions:

Each ball is not distinguished from the other.

Each box is not distinguished from the other.

Each ball can go into only one box and no one remains outside of the boxes.

Each box can contain an arbitrary number of balls (including zero).

Note that you must print this count modulo $10^9+7$.

Input

$n$ $k$

The first line will contain two integers $n$ and $k$.

Output

Print the number of ways modulo $10^9+7$ in a line.

Constraints

$1 \le n \le 1000$

$1 \le k \le 1000$

Sample Input 1

5 3

Sample Output 1

5

Sample Input 2

10 5

Sample Output 2

30

Sample Input 3

100 100

Sample Output 3

190569292


import java.util.Scanner;

class Main
{
	int st[];
	int minVal(int x, int y) {
		return (x < y) ? x : y;
	}

	int getMid(int s, int e) {
		return s + (e - s) / 2;
	}

	int RMQUtil(int ss, int se, int qs, int qe, int index)
	{

		if (qs <= ss && qe >= se)
			return st[index];

		if (se < qs || ss > qe)
			return Integer.MAX_VALUE;

		int mid = getMid(ss, se);
		return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
				RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
	}

	int RMQ(int n, int qs, int qe)
	{

		if (qs < 0 || qe > n - 1 || qs > qe) {
			System.out.println("Invalid Input");
			return -1;
		}

		return RMQUtil(0, n - 1, qs, qe, 0);
	}

	int constructSTUtil(int arr[], int ss, int se, int si)
	{

		if (ss == se) {
			st[si] = arr[ss];
			return arr[ss];
		}

		int mid = getMid(ss, se);
		st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
				constructSTUtil(arr, mid + 1, se, si * 2 + 2));
		return st[si];
	}

	void constructST(int arr[], int n)
	{

		int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));

		int max_size = 2 * (int) Math.pow(2, x) - 1;
		st = new int[max_size];

		constructSTUtil(arr, 0, n - 1, 0);
	}

	public static void main(String args[])
	{

		Scanner sc = new Scanner(System.in);
		String N = sc.next();
		String slide = sc.next();
		Main tree = new Main();
		int arr[] = new int[Integer.parseInt(N)];
		for(int i=0; i<Integer.parseInt(N); i++)
		{
			arr[i] = Integer.parseInt(sc.next());
		}

		tree.constructST(arr, Integer.parseInt(N));

		for(int i=0;i<=Integer.parseInt(N) - Integer.parseInt(slide);i++) {
			int result=tree.RMQ(Integer.parseInt(N), i, i+Integer.parseInt(slide)-1);
			if(i!= Integer.parseInt(N) - Integer.parseInt(slide)){
					System.out.print(result+" ");
				}else{
					System.out.println(result);
				}
		}
	}
}

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

Sliding Minimum Element

For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $L$, find the minimum of each possible sub-arrays with size $L$ and print them from the beginning. For example, for an array $\{1, 7, 7, 4, 8, 1, 6\}$ and $L = 3$, the possible sub-arrays with size $L = 3$ includes $\{1, 7, 7\}$, $\{7, 7, 4\}$, $\{7, 4, 8\}$, $\{4, 8, 1\}$, $\{8, 1, 6\}$ and the minimum of each sub-array is 1, 4, 4, 1, 1 respectively.

Constraints

$1 \leq N \leq 10^6$

$1 \leq L \leq 10^6$

$1 \leq a_i \leq 10^9$

$L \leq N$

Input

The input is given in the following format.

$N$ $L$

$a_1$ $a_2$ ... $a_N$

Output

Print a sequence of the minimum in a line. Print a space character between adjacent elements.

Sample Input 1

7 3
1 7 7 4 8 1 6

Sample Output 1

1 4 4 1 1


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

class Main {

	static final int INF = Integer.MAX_VALUE/2;
	public static final Comparator<Node> COMPARATOR = new Comp();

	private static class Comp implements Comparator<Node>{
		public int compare(Node x,Node y){
			return (x.d > y.d) ? 1 : ((x.d == y.d) ? 0 : -1);
		}
	}

	static class Node {
		int id;
		int d;
		Node(int id,int d){
			this.id = id;
			this.d = d;
		}
	}

	static class Edge {
		int to;
		int cost;
		Edge(int to,int cost){
			this.to = to;
			this.cost = cost;
		}
	}

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

		String line = br.readLine();
		String[] str = line.split(" ");
		int v = Integer.parseInt(str[0]);
		int e = Integer.parseInt(str[1]);
		int r = Integer.parseInt(str[2]);

		LinkedList<LinkedList<Edge>> graph = new LinkedList<LinkedList<Edge>>();
		for (int i=0; i<v; i++) {
			graph.add(new LinkedList<Edge>());
		}

		for (int i=0; i<e; i++) {
			line = br.readLine();
			str = line.split(" ");
			int si = Integer.parseInt(str[0]);
			int ti = Integer.parseInt(str[1]);
			int di = Integer.parseInt(str[2]);
			LinkedList<Edge> list = graph.get(si);
			list.add(new Edge(ti,di));
		}

		PriorityQueue<Node> pQue = new PriorityQueue<Node>(100000,COMPARATOR);
		int[] d = new int[v];
		Arrays.fill(d,INF);
		d[r] = 0;
		pQue.add(new Node(r,0));

		while (!pQue.isEmpty()) {
			Node node = pQue.poll();
			int now = node.id;
			if (d[now] < node.d)
				continue;
			LinkedList<Edge> list = graph.get(now);
			while (!list.isEmpty()) {
				Edge edge = list.poll();
				if (d[edge.to] > d[now] + edge.cost) {
					d[edge.to] = d[now] + edge.cost;
					pQue.add(new Node(edge.to,d[edge.to]));
				}
			}
		}

		for (int i : d) {
			System.out.println(i==INF?"INF":i);
		}

		br.close();
	}
}

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
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. r is the source of the graph.

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

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author silviase
 */
public class Main {

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

    static class DijkstraVerify {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int source = in.nextInt();
            Graph g = new Graph(n);
            for (int i = 0; i < m; i++) {
                g.addEdge(new Edge(in.nextInt(), in.nextInt(), in.nextInt()));
            }
            long[] d = g.dijkstra(source);
            for (int i = 0; i < n; i++) {
                if (d[i] > 1e15) out.println("INF");
                else out.println(d[i]);
            }
        }

    }

    static class Graph {
        public int size;
        public ArrayList<Edge>[] adj;
        public int[] inDeg;
        public int[] vertexCost;

        @SuppressWarnings("unchecked")
        public Graph(int size) {
            this.size = size;
            adj = new ArrayList[size];
            inDeg = new int[size];
            vertexCost = new int[size];
            for (int i = 0; i < size; i++) {
                adj[i] = new ArrayList<>();
            }
        }

        public void addEdge(Edge e) {
            adj[e.from].add(e);
            inDeg[e.to]++;
        }

        public long[] dijkstra(int from) {
            long[] d = new long[size];
            PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparing(e -> d[e]));
            for (int i = 0; i < size; i++) {
                d[i] = (i == from) ? 0 : (long) 1e18;
                pq.add(i);
            }
            // System.out.println(Arrays.toString(pq.toArray()));
            while (!pq.isEmpty()) {
                int search = pq.poll();
                // System.out.println("now: " + search);
                ArrayList<Edge> edges = adj[search];
                for (Edge e : edges) {
                    // System.out.println(e.toString());
                    long cmp = d[search] + e.cost;
                    if (d[e.to] > d[search] + e.cost) {
                        // 更新が入る
                        // 処理を入れたい場合はここに入れる
                        d[e.to] = d[search] + e.cost;
                        pq.add(e.to);
                    }
                }
                //  System.out.println(Arrays.toString(pq.toArray()));
            }
            return d;
        }

    }

    static class Edge {
        public int from;
        public int to;
        public long cost;

        public Edge(int to) {
            this.to = to;
        }

        public Edge(int to, long cost) {
            this.to = to;
            this.cost = cost;
        }

        public Edge(int from, int to, long cost) {
            this.from = from;
            this.to = to;
            this.cost = cost;
        }

        public String toString() {
            return "Edge{" +
                    "from=" + from +
                    ", to=" + to +
                    ", cost=" + cost +
                    '}';
        }

    }
}


import java.util.Scanner;

import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

class Main{

    public static void main(String[] arg){

        Scanner in = new Scanner(System.in);

        String input = in.nextLine();
        String [] param_line = input.split(" ", 0);

        double x1 = Double.parseDouble(param_line[0]);
        double y1 = Double.parseDouble(param_line[1]);
        double x2 = Double.parseDouble(param_line[2]);
        double y2 = Double.parseDouble(param_line[3]);

        double d = sqrt(pow(x2-x1,2)+pow(y2-y1, 2));

        System.out.println(d);
    }
}

Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


import java.util.Scanner;
public class Main {
    public static void main(String[] args){
    	Scanner scan = new Scanner(System.in);
    	int[] dice_num,dice_num2;
    	dice_num = new int[10];
    	dice_num2 = new int[10];
    	int i;
    	for(i = 0; i < 6; i++){
    		dice_num[i] = scan.nextInt();
    	}
    	String dir_word = scan.next();
    	String dir_array[] = dir_word.split("");
    	for(i = 0; i < dir_word.length(); i++){
    		if(dir_array[i].equals("S")){
    			dice_num2[0] = dice_num[4];
    			dice_num2[1] = dice_num[0];
    			dice_num2[2] = dice_num[2];
    			dice_num2[3] = dice_num[3];
    			dice_num2[4] = dice_num[5];
    			dice_num2[5] = dice_num[1];
    		}
    		else if(dir_array[i].equals("W")){
    			dice_num2[0] = dice_num[2];
    			dice_num2[1] = dice_num[1];
    			dice_num2[2] = dice_num[5];
    			dice_num2[3] = dice_num[0];
    			dice_num2[4] = dice_num[4];
    			dice_num2[5] = dice_num[3];
    		}
    		else if(dir_array[i].equals("N")){
    			dice_num2[0] = dice_num[1];
    			dice_num2[1] = dice_num[5];
    			dice_num2[2] = dice_num[2];
    			dice_num2[3] = dice_num[3];
    			dice_num2[4] = dice_num[0];
    			dice_num2[5] = dice_num[3];
    		}
    		else if(dir_array[i].equals("E")){
    			dice_num2[0] = dice_num[3];
    			dice_num2[1] = dice_num[1];
    			dice_num2[2] = dice_num[0];
    			dice_num2[3] = dice_num[5];
    			dice_num2[4] = dice_num[4];
    			dice_num2[5] = dice_num[2];
    		}
    			dice_num[0] = dice_num2[0];
    			dice_num[1] = dice_num2[1];
    			dice_num[2] = dice_num2[2];
    			dice_num[3] = dice_num2[3];
    			dice_num[4] = dice_num2[4];
    			dice_num[5] = dice_num2[5];
    			System.out.println(dice_num[0]);
    	}
    		System.out.println(dice_num[0]);
    	}
}

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

Dice I

Write a program to simulate rolling a dice, which can be constructed by the following net.

As shown in the figures, each face is identified by a different label from 1 to 6.

Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.

In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.

Output

Print the integer which appears on the top face after the simulation.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

$0 \leq $ the length of the command $\leq 100$

Sample Input 1

1 2 4 8 16 32
SE

Sample Output 1

8

You are given a dice where 1, 2, 4, 8, 16 are 32 are assigned to a face labeled by 1, 2, ..., 6 respectively. After you roll the dice to the direction S and then to the direction E, you can see 8 on the top face.

Sample Input 2

1 2 4 8 16 32
EESWN

Sample Output 2

32


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		class qube{
			Scanner sc = new Scanner(System.in);
			int [] face = new int[6],faces;
			Integer i,dump=0;
			Integer a,b,n;

			qube(){
				for(i=0;i<6;i++){
					face[i]=sc.nextInt();
				}
				n = sc.nextInt();
				faces = face.clone();
			}

			void swap(int a,int b){
				dump = this.face[a];
				this.face[a] = this.face[b];
				this.face[b] = dump;

			}
			void scn(){
				a = sc.nextInt();
				b = sc.nextInt();
			}
			void pt(){
				System.out.printf("%d\n", this.face[2]);
			}

			void move(String es){
				if(es.equals("E")){
					swap(0,2);
					swap(0,5);
					swap(0,3);
				}
				else if(es.equals("N")){
					swap(4,5);
					swap(4,1);
					swap(4,0);
				}

			}

		}
		int j;

		qube q = new qube();
		for(j=0;j<q.n;j++){
			q.scn();
			while(true){
				if(q.a.equals(q.face[1])){
					break;
				}
				q.move("N");
			}while(true){
				if(q.b.equals(q.face[0])){
					break;
				}
				q.move("E");
			}
			q.pt();
			q.face = q.faces.clone();
		}

	}

}

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

Dice II

Construct a dice from a given sequence of integers in the same way as Dice I.

You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, the number of questions $q$ is given.

In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.

Output

For each question, print the integer on the right side face.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

The integers are all different

$1 \leq q \leq 24$

Sample Input

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

Sample Output

3
5
6


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

public class Main {

	private static class Dice {
		private String top;
		private String bottom;
		private String front;
		private String back;
		private String left;
		private String right;

		public Dice(
				String top,
				String front,
				String right,
				String left,
				String back,
				String bottom)
		{
			this.top = top;
			this.front = front;
			this.right = right;
			this.left = left;
			this.back = back;
			this.bottom = bottom;
		}

		public String operationE() {
			String tmp = this.top;
			this.top = this.left;
			this.left = this.bottom;
			this.bottom = this.right;
			this.right = tmp;

			return this.top;
		}

		public String operationN() {
			String tmp = this.top;
			this.top = this.front;
			this.front = this.bottom;
			this.bottom = this.back;
			this.back = tmp;

			return this.top;
		}

		public String operationS() {
			String tmp = this.top;
			this.top = this.back;
			this.back = this.bottom;
			this.bottom = this.front;
			this.front = tmp;

			return this.top;
		}

		public String operationW() {
			String tmp = this.top;
			this.top = this.right;
			this.right = this.bottom;
			this.bottom = this.left;
			this.left = tmp;

			return this.top;
		}

		public String getTop() {
			return top;
		}

		public String getBottom() {
			return bottom;
		}

		public String getFront() {
			return front;
		}

		public String getBack() {
			return back;
		}

		public String getLeft() {
			return left;
		}

		public String getRight() {
			return right;
		}

	}

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

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

		Dice dice1 = new Dice(label1[0], label1[1], label1[2], label1[3], label1[4], label1[5]);
		Dice dice2 = new Dice(label2[0], label2[1], label2[2], label2[3], label2[4], label2[5]);

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

			dice2.operationS();

			for (int j = 0; j < 4; j++) {

				dice2.operationW();

				if (dice1.getTop().equals(dice2.getTop()) &&
					dice1.getBottom().equals(dice2.getBottom()) &&
					dice1.getFront().equals(dice2.getFront()) &&
					dice1.getBack().equals(dice2.getBack()) &&
					dice1.getRight().equals(dice2.getRight()) &&
					dice1.getLeft().equals(dice2.getLeft()))
				{

					System.out.println("Yes");
					return;

				}
			}
		}

		dice2.operationW();

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

			dice2.operationS();

			for (int j = 0; j < 4; j++) {

				dice2.operationW();

				if (dice1.getTop().equals(dice2.getTop()) &&
					dice1.getBottom().equals(dice2.getBottom()) &&
					dice1.getFront().equals(dice2.getFront()) &&
					dice1.getBack().equals(dice2.getBack()) &&
					dice1.getRight().equals(dice2.getRight()) &&
					dice1.getLeft().equals(dice2.getLeft()))
				{

					System.out.println("Yes");
					return;

				}
			}
		}

		System.out.println("No");

	}
}

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

Dice III

Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical.

Input

In the first line, six integers assigned to faces of a dice are given in ascending order of their corresponding labels.

In the second line, six integers assigned to faces of another dice are given in ascending order of their corresponding labels.

Output

Print "Yes" if two dices are identical, otherwise "No" in a line.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

Sample Input 1

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

Sample Output 1

Yes

Sample Input 2

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

Sample Output 2

No


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

    String value;
    int input;
    int output;

    System.out.println("test");
    value = new java.util.Scanner(System.in).nextLine();
    input=Integer.parseInt(value);
    output=(int)(Math.pow((double)input,3));
    System.out.println(output);
    }
}

X Cubic

Write a program which calculates the cube of a given integer x.

Input

An integer x is given in a line.

Output

Print the cube of x in a line.

Constraints

1 ≤ x ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27


import java.util.Scanner;
class Main{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		int x = scan.nextInt();
		x = x*x*x;
		System.out.println(x);
	}
}


import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(n*n*n);
    }
}


import java.util.Scanner;

public class Main{

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

        int x = sc.nextInt();
        int answer = x*x*x;
        System.out.println(answer);
        sc.close();
}

}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        sc.close();
        System.out.println(n * n * n);
    }
}


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

	int numberA = sc.nextInt();

    System.out.println((int)(Math.pow(numberA,3)));
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        int a, b, area, perimeter;
        Scanner scan = new Scanner(System.in);

        a = scan.nextInt();
        b = scan.nextInt();
        area = a * b;
        perimeter = (a + b) * 2;

        System.out.print(area);
        System.out.print(' ');
        System.out.println(perimeter);

    }
}

Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

The length a and breadth b of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

1 ≤ a, b ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16


import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a;
a=sc.nextInt();
int b;
b=sc.nextInt();
System.out.print(a * b);
System.out.print(2 * a + 2 * b);
}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		int area = a * b;
		int length = (a + b) * 2;
		System.out.println( area+" "+ length);
	}
}


import java.util.Scanner;

class Main {
   public static void main(String[] args) {
      int a,b,c,d;
      Scanner sc = new Scanner(System.in);
      a = sc.nextInt();
      b = sc.nextInt();
      c = a*b;
      d = 2*(a+b);
      System.out.println( c + " " + d );
   }
}


import java.util.Scanner;

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

        System.out.println(a * b + " " + 2 * (a + b));
        sc.close();
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		try(Scanner sc = new Scanner(System.in)){
			int s = sc.nextInt();
			if(s >=0 && s <86400) {
				int second = s % 60;
				s = s / 60;
				int minute = s % 60;
				int hour = s / 60;
				System.out.println(String.format("%d:%d:%d",hour,minute,second));
			}
		}
	}
}

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

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


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

class Main{
  public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int s = n%60;
    int h = n/3600;
    int m = (n-h*3600)/60;
    System.out.println(h+":"+m+":"+s);
  }
}


import java.util.Scanner;

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

		int h = S / 3600;
		int m = (S - (h * 3600)) / 60;
		int s = (S - (h * 3600))- m * 60;

		System.out.println(h + ":" + m + ":" + s);
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);;
        int a = sc.nextInt();
        int b = sc.nextInt();
        if(a>b){
            System.out.println("a"+" > "+"b");
        }else if(a<b) {
            System.out.println("a"+" < "+"b");
        }else{
            System.out.println("a"+" == "+"b");
        }
    }

}

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


import java.util.Scanner;

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

		if(a<b){
			System.out.println("a<b");
		}else if(a>b){
			System.out.println("a>b");
		}else if(a==b){
			System.out.println("a==b");
		}else {
			System.out.print("0");
		}
	}

}


import java.util.Scanner;

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

        int a = inp.nextInt();

        int b = inp.nextInt();

        if (a == b) {
            System.out.println("a == b");
        } else if (a < b) {
            System.out.println("a < b");
        } else if (a > b) {
            System.out.println("a > b");
        }
    }
}


import java.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner kb = new Scanner( System.in);
		int a=kb.nextInt();
		int b=kb.nextInt();
		int c=kb.nextInt();

		if( a < b ) {
			if( b < c ) {
				System.out.println( "Yes");
			} else {
				System.out.println( "No");
			}
		} else {
			System.out.println( "No");
		}
	}
}

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


import java.util.*;

class Main {
	static Scanner sc =new Scanner(System.in);
	static int a;
	static int b;
	static int c;
    static int [] x;
		public static void main (String[]agrs){
			a=sc.nextInt();
			b=sc.nextInt();
			c=sc.nextInt();
			int[]x=new int[]{a,b,c};

			Arrays.sort(x);
			for(int i = 0;i<x.length;i++){
				System.out.println(" "+x[i]);
			}
		}
}

Sorting Three Numbers

Write a program which reads three integers, and prints them in ascending order.

Input

Three integers separated by a single space are given in a line.

Output

Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8


import java.util.Scanner;

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

		Scanner scan = new Scanner(System.in);
		int W = scan.nextInt();
		int H = scan.nextInt();
		int x = scan.nextInt();
		int y = scan.nextInt();
		int r = scan.nextInt();

		if( x > r && y - r >0 && x + r < W && y + r < H ) {
			System.out.println("Yes");
		} else {
			System.out.println("No");
		}

	}

}

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

Circle in a Rectangle

Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100 \leq x, y \leq 100$

$ 0 < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No


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

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

		ArrayList<String> list = new ArrayList<String>();

		for (int i = 0; i < 10001; i++) {
			list.add(br.readLine());
			if ("0".equals(list.get(i))) {
				for (int j = 1; j < list.size(); j++) {
					System.out.println("Case "+j+": "+list.get(j-1));
				}
				break;
			}
		}
	}
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


import java.util.Scanner;
class Main {
    public static void main(String[] args){
       Scanner scan = new Scanner(System.in);
       int x;
       for(int i = 0; i < 10000; i++){
         x = scan.nextInt();
         if(x == 0) break;

         System.out.println("Case " + i + ": " + x);
       }
    }
}


import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int i = 1;
        for(;i<20000;i++){
            int x = sc.nextInt();
            if(x == 0){
                break;
            }
            else{
                System.out.println("Case "+i+": "+x);
            }

        }

    }
}


import java.util.Scanner;
public class Main {
        public static void main(String[] args) {
            int i=1;
            Scanner sc = new Scanner(System.in);
        while(true){
                int x = sc.nextInt();
                  if(x==0){
                      break;
                   }
                   System.out.printf("Case %d: %d\n",i,x);
                  i++;
                  }
            }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = 1;
        while(true) {
            int n = sc.nextInt();
        	if(n == 0) {
        		break;
        	}
        	System.out.printf("Case %d: %d\n", i, n);
        	i ++;
        }
    }
}


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

public class Main {
	public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder();
        for(int i=1;i<=1000;i++){
        	String items[]=reader.readLine().split(" ");
        	sb.append(items[1] + " " + items[0]+ "\n");
        	int num1=Integer.parseInt(items[0]);
        	int num2=Integer.parseInt(items[1]);
            if(num1==0 && num2==0){
            	break;
            }
        }
        System.out.println(sb);
	}
}

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


import java.util.Scanner;

/**
 *
 * @author k16069kk
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        int count = 0;

        for (int i = a; i <= b; i++) {
            if(c%i == 0) count++;
        }
        System.out.println(count);
    }

}

How Many Divisors?

Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.

Input

Three integers a, b and c are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


import java.util.*;

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

        //入力準備
        Scanner sc = new Scanner(System.in);

        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int cnt = 0;

        //配列にデータを入れる
        for(int i = a; i <= b; i++ ){
            if(c % i == 0){
                cnt++;
            }
        }
        System.out.println(cnt);
    }
}


import java.util.*;
class Main{
	Scanner sc=new Scanner(System.in);
	int a,b;
	void g(){
		a=sc.nextInt();
		b=sc.nextInt();

		System.out.println(a/b);
		System.out.println(a%b);
		System.out.println((float)a/b);

	}

	public static void main(String[]agrs){
		new Main().g();
	}
}

A/B Problem

Write a program which reads two integers a and b, and calculates the following values:

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str[] = br.readLine().split(" ");
        int a = Integer.parseInt(str[0]);
        int b = Integer.parseInt(str[1]);
        System.out.printf("%d %d %.5f\n",a/b,a%b,(double)a/(double)b);

    }
}


import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		int d = a / b;
		int r = a % b;
		float f = (float)a / (float)b;
		System.out.printf("%d %d %05f", d, r, f);
	}
}


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

public class Main {

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

		String data[] = br.readLine().split(" ");
		int a = Integer.parseInt(data[0]);
		int b = Integer.parseInt(data[2]);

		String s = (data[1]);

		if (s.equals("+")) {
			System.out.println(a + b);
			}
		if (s.equals("-")) {
			System.out.println(a - b);
			}

		if (s.equals("*")) {
			System.out.println(a * b);
			}
		if (s.equals("/")) {
			System.out.println(a / b);
			}

	}

}

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

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

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


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

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		long total = 0;
		ArrayList<Integer> list = new ArrayList<Integer>();

		for (int i = 0; i < n; i++) {
			list.add(sc.nextInt());
		}
		//????????§???????????????
		Collections.sort(list);
		for (int i = 0; i < list.size(); i++) {
			total += list.get(i);
		}
		//????°????????????§??????????¨???????????????????
		System.out.println(list.get(0) +" "+ list.get(list.size()-1) +" "+ total);
	}
}

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

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int M=1000000,m=-1000000;
		long S = 0;

		for(int i = 1;i <= n;i++){
			int x = sc.nextInt();
			M = Math.max(M, x);
			m = Math.min(m, x);
			S = S+x;
		}
		System.out.print(m+" "+M+" "+S);
	}
}


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

public class Main {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();

		int count = Integer.parseInt(br.readLine());
        String[] strArray = new String[count];
        strArray = br.readLine().split(" ");

        int max=-1000000, min=1000000, sum=0;
        int a = 0;

        for(String str : strArray) {
        	a = Integer.parseInt(str);
        	max = Math.max(max, a);
        	min = Math.min(min, a);
        	sum += a;
        }

        System.out.print(min + " " + max + " " + sum);
	}
}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		while(true){
			int H=sc.nextInt();
			int W=sc.nextInt();

			if(H==0&&W==0) {
				break;
			}

			for(int i=0; i<H; i++) {
				for(int j=0; j<W; j++) {
					System.out.printf("#");
				}
				System.out.printf("%n");
			}

			System.out.printf("%n");
		}
	}

}

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

####
####
####

######
######
######
######
######

##
##


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            int H = sc.nextInt();
            int W = sc.nextInt();
            if (H == 0 && W == 0) {
                break;
            }
            for ( int i = 0; i < H; i++ ){
                for ( int j = 0; j < W; j++ ){
                    System.out.print("#");
                }
                System.out.println("");
            }
            System.out.println("");
        }

    }
}


import java.util.Scanner;

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

    		while(true){
    	    	int a = sc.nextInt();
    	    	int b = sc.nextInt();
    		if(a==0 && b==0){
    			break;
    		}else{
    			for(int x=1;x<=a;x++){
    		for(int y=1;y<=b;y++){
    		if(x==1){
    		System.out.print("#");
    		}else if(x==a){
    		System.out.print("#");
    		}else if(y==1 || y==b){
    		System.out.print("#");
    		}else if(y<b){
    		System.out.print(".");
    		}
    		}
    		System.out.println("");
    		}
    		}
    }
}
}

Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

##########
#........#
#........#
#........#
#........#
##########

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Constraints

3 ≤ H ≤ 300

3 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
0 0

Sample Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(true) {
            int h = scanner.nextInt();
            int w = scanner.nextInt();
            if (h == 0 && w == 0) break;
            for (int i = 0; i < w; i++) {
                System.out.print("#");
            }
            System.out.print("\n");
            for (int i = 0; i < h - 2; i++) {
                System.out.print("#");
                for (int j = 0; j < w - 2; j++) {
                    System.out.print(".");
                }
                System.out.print("#");
                System.out.print("\n");
            }
            for (int i = 0; i < w; i++) {
                System.out.print("#");
            }
            System.out.print("\n");
            System.out.print("\n");
        }
        scanner.close();
    }
}


import java.util.Scanner;
public class Main{
  public static void main(String[]args){
    Scanner sc = new Scanner(System.in);
    while(true){
      int H = sc.nextInt();
      int W = sc.nextInt();
      if(H == 0 && W == 0)
      break;
      for(int i = 0;i < H;i++){
        for(int j = 0;j < W;j++){
          if((i+j)%2==1){
          System.out.print(".");
        }else {
          System.out.print("#");
        }
        }
        System.out.print("\n");
      }
      System.out.println("");
    }
}
}

Print a Chessboard

Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.

#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#

Note that the top left corner should be drawn by '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the chessboard made of '#' and '.'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

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

Sample Output

#.#.
.#.#
#.#.

#.#.#.
.#.#.#
#.#.#.
.#.#.#
#.#.#.

#.#
.#.
#.#

#.
.#

#


import java.util.Scanner;

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

		while(true)
		{
			int H = stdIn.nextInt();
			int W = stdIn.nextInt();

			if(H==0 && W==0)
			{
				break;
			}

			for(int i=0;i<H;i++)
			{
				for(int j=0;j<W;j++)
				{
					if((i+j)%2==0)
					{
						System.out.print('#');
					}
					else
					{
						System.out.print('.');
					}
				}
				System.out.println();
			}
			System.out.println();
		}
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner a = new Scanner(System.in);
		int h =1;
		int w = 1;

		while(h > 0 && w > 0){
			h = a.nextInt();
			w = a.nextInt();
			for(int i = 0;i < h;i++){
				for(int j = 0;j < w;j++){
					if((i % 2) == 0){
						System.out.print("#");
						System.out.print(".");
					}else{
						System.out.print(".");
						System.out.print("#");
					}
				}
				if(h != 0 && w != 0)
					System.out.println();
			}
			if(h != 0 && w != 0)
				System.out.println();
		}
	}

}


import java.io.*;

public class Main {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        String input;
        while (!(input = br.readLine()).equals("0 0")) {
            String[] st = input.split(" ");
            int a = Integer.parseInt(st[0]);
            int b = Integer.parseInt(st[1]);
            for (int i = 0; i < a; i++) {
                if (i % 2 == 0) {
                    for (int j = 0; j < b; j++) {
                        bw.append(j % 2 == 0 ? "#" : ".");
                    }
                } else {
                    for (int j = 0; j < b; j++) {
                        bw.append(j % 2 == 0 ? "." : "#");
                    }
                }
                bw.newLine();
            }
            bw.newLine();
        }
        bw.flush();
    }

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 1; i <= n; i++) {
			if (i % 3 == 0 || i % 10 == 3 || i % 10 == 0) {
				int[] data = { i };
				for (int data1 : data) {
					System.out.print(" " + data1);
				}
			}
		}
		System.out.println("");
	}
}

Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;

cout << endl;
}

Input

An integer n is given in a line.

Output

Print the output result of the above program for given integer n.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

3 6 9 12 13 15 18 21 23 24 27 30

Put a single space character before each element.


import java.util.Scanner;

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

		for(long i = 1;i <= n;i++){
			long x = i;
			if(x % 3 == 0 || x % 10 == 3){
				System.out.print(" "+i);
				continue;
			}else{
				for(x /= 10;x != 0;x /= 10){
					if(x % 10 == 3)
						System.out.print(" "+i);
						break;
				}
			}
		}

		System.out.print("\n");

		sc.close();
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		int n = Integer.parseInt(line);
		int i = 1;
		while (i <= n) {
			if (i % 3 == 0) {
				System.out.print(" " + i);
			} else if (i % 10 == 3) {
				System.out.print(" " + i);
			}
			i++;
		}
	}
}


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

public class Main {

	public static final int BIG_NUM  = 2000000000;
	public static final int MOD  = 1000000007;

	public static void main(String[] args) {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		try {
			int N = Integer.parseInt(br.readLine());

			int x;

			for(int i = 1; i <= N; i++)
			{
				if(i%3 == 0){
					System.out.printf(" %d",i);
				}else{
					x = i;
					do{
						if(x%10 == 3){
							System.out.printf(" %d",i);
							break;
						}
						x /=10;
					}while(x != 0);
				}
			}
			System.out.printf("\n");

		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        ArrayList<Integer> ls = new ArrayList<>();

        for (int i = 0; i < n; i++) ls.add(scan.nextInt());

        Collections.reverse(ls);
        for (int i = 0; i < ls.size(); i++) {
            System.out.print(i == ls.size() -1? ls.get(i) : ls.get(i) + " ");
        }
        System.out.println();
    }
}

Reversing Numbers

Write a program which reads a sequence and prints it in the reverse order.

Input

The input is given in the following format:

n
a1 a2 . . . an

n is the size of the sequence and ai is the ith element of the sequence.

Output

Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).

Constraints

n ≤ 100

0 ≤ ai < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = Integer.parseInt(s.nextLine());
		boolean flag=true;
		int[] seq = new int[n];
		if(n<=100) {

		for(int i=0;i<n;i++) {
			seq[i]=s.nextInt();
			if(seq[i]>=0 && seq[i]<1000) {
				continue;
			}else {
				flag=false;
				break;
			}
		}
		}

		if(flag==true) {
			for(int j=n;j>0;j--) {
				System.out.print(seq[j-1]);
				if(j!=1)
				System.out.print(" ");
			}
		}

	}

}


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];
        int b[] = new int[n];
        int c;
        for(int i = 0; i < n; i++){
        	c = sc.nextInt();
        	a[i] = c;
        	b[i] = c;
        }
        for(int i = 0; i < n; i++){
        	a[i] = b[n - i - 1];
        	System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}


import java.util.Scanner;

class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        String str[] = sc.nextLine().split(" ");
        for(int i=n-1;i>=0;i--){
            if(i==0){
                System.out.print(str[i]);
            }else{
                System.out.print(str[i]+" ");
            }
        }
        System.out.println();
    }
}