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

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

	long MODULO = 1_000_000_000 + 7;

	void run() {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[][] e = new int[n][3];
		for (int i = 0; i < n; ++i) {
			e[i][0] = sc.nextInt();// x
			e[i][1] = sc.nextInt();// v
			e[i][2] = -1;
		}
		Arrays.sort(e, new Comparator<int[]>() {
			@Override
			public int compare(int[] o1, int[] o2) {
				return Integer.compare(o1[1], o2[1]);
			}
		});
		for (int i = 0; i < n; ++i) {
			e[i][2] = i;
		}

		Arrays.sort(e, new Comparator<int[]>() {
			@Override
			public int compare(int[] o1, int[] o2) {
				return Integer.compare(o1[0], o2[0]);
			}
		});

		int[][] min = new int[n][2];
		int[][] max = new int[n][2];
		for (int i = 0; i < n; ++i) {
			min[i][0] = Integer.MAX_VALUE / 16;
			max[i][0] = -Integer.MAX_VALUE / 16;
			min[i][1] = -1;
			max[i][1] = -1;
		}
		for (int i = 0; i < n; ++i) {
			if (i == 0 || max[i - 1][0] < e[i][1]) {
				max[i][0] = e[i][1];
				max[i][1] = e[i][2];
			} else {
				max[i][0] = max[i - 1][0];
				max[i][1] = max[i - 1][1];
			}
		}
		for (int i = n - 1; i >= 0; --i) {
			if (i == n - 1 || min[i + 1][0] > e[i][1]) {
				min[i][0] = e[i][1];
				min[i][1] = e[i][2];
			} else {
				min[i][0] = min[i + 1][0];
				min[i][1] = min[i + 1][1];
			}
		}

		long[] f = new long[n];
		long s = 0;
		int t = 0;
		for (int i = 0; i < n; ++i) {
			while (max[t][1] < min[i][1]) {
				s = (s - f[t] + MODULO) % MODULO;
				++t;
			}
			f[i] = s;
			if (min[i][1] == min[0][1]) {
				++f[i];
			}
			s += f[i];
			s %= MODULO;
			f[i] %= MODULO;
		}
		long ans = 0;
		for (int i = 0; i < n; ++i) {
			if (max[n - 1][1] == max[i][1]) {
				ans += f[i];
			}
			while (ans >= MODULO) {
				ans -= MODULO;
			}
		}
		System.out.println(ans);
	}

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

}

Score : 1200 points

Problem Statement

Takahashi is an expert of Clone Jutsu, a secret art that creates copies of his body.

On a number line, there are N copies of Takahashi, numbered 1 through N.
The i-th copy is located at position X_i and starts walking with velocity V_i in the positive direction at time 0.

Kenus is a master of Transformation Jutsu, and not only can he change into a person other than himself, but he can also transform another person into someone else.

Kenus can select some of the copies of Takahashi at time 0, and transform them into copies of Aoki, another Ninja.
The walking velocity of a copy does not change when it transforms.
From then on, whenever a copy of Takahashi and a copy of Aoki are at the same coordinate, that copy of Takahashi transforms into a copy of Aoki.

Among the 2^N ways to transform some copies of Takahashi into copies of Aoki at time 0, in how many ways will all the copies of Takahashi become copies of Aoki after a sufficiently long time?
Find the count modulo 10^9+7.

Constraints

1 ≤ N ≤ 200000

1 ≤ X_i,V_i ≤ 10^9(1 ≤ i ≤ N)

X_i and V_i are integers.

All X_i are distinct.

All V_i are distinct.

Input

The input is given from Standard Input in the following format:

N
X_1 V_1
:
X_N V_N

Output

Print the number of the ways that cause all the copies of Takahashi to turn into copies of Aoki after a sufficiently long time, modulo 10^9+7.

Sample Input 1

3
2 5
6 1
3 7

Sample Output 1

6

All copies of Takahashi will turn into copies of Aoki after a sufficiently long time if Kenus transforms one of the following sets of copies of Takahashi into copies of Aoki: (2), (3), (1,2), (1,3), (2,3) and (1,2,3).

Sample Input 2

4
3 7
2 9
8 16
10 8

Sample Output 2

9


import java.util.Scanner;
public class Main{
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int x = sc.nextInt();
    int y = sc.nextInt();
    int a = group(x);
    int b = group(y);
    if(a == b) System.out.println("Yes");
    else System.out.println("No");
  }
  public static int group(int a) {
    if(a == 2) return 1;
    else if(a == 4 || a == 6 || a == 9 || a == 11) return 2;
    else return 3;
  }
}

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

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No

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 static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;

public class Main {

	void solve() {
		int N = sc.nextInt();
		int[] A = sc.nextIntArray(3 * N);

		long[] B = new long[3 * N + 1];
		long[] C = new long[3 * N + 1];

		{
			PriorityQueue<Integer> q= new PriorityQueue<>();
			long sum = 0;
			for (int i = 0; i < N; i++) {
				sum += A[i];
				q.add(A[i]);
			}
			for (int i = N; i <= 3 * N; i++) {
				B[i] = sum;
				if (i < 3 * N) {
					sum += A[i];
					q.add(A[i]);
					sum -= q.poll();
				}
			}
//			tr(B);
		}
		{
			PriorityQueue<Integer> q = new PriorityQueue<>();
			long sum = 0;
			for (int i = 3*N-1; i >= 2*N; i--) {
				sum += A[i];
				q.add(-A[i]);
			}
			for (int i = 2*N-1; i >= 0; i--) {
				C[i+1] = sum;
				sum += A[i];
				q.add(-A[i]);
				sum += q.poll();
			}
			C[0] = sum;
//			tr(C);
		}
		long ans = -(1L << 58);
		for (int i = N; i <= 2*N; i++) {
			ans = max(B[i] - C[i], ans);
		}
		out.println(ans);
	}

	static void tr(Object... os) { System.err.println(deepToString(os)); }
	static void tr(int[][] as) { for (int[] a : as) tr(a); }

	void print(int[] a) {
		out.print(a[0]);
		for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
		out.println();
	}

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

	MyScanner sc = null;
	PrintWriter out = null;
	public void run() throws Exception {
		sc = new MyScanner(System.in);
		out = new PrintWriter(System.out);
		for (;sc.hasNext();) {
			solve();
			out.flush();
		}
		out.close();
	}

	class MyScanner {
		String line;
		BufferedReader reader;
		StringTokenizer tokenizer;

		public MyScanner(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			tokenizer = null;
		}
		public void eat() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					line = reader.readLine();
					if (line == null) {
						tokenizer = null;
						return;
					}
					tokenizer = new StringTokenizer(line);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		public String next() {
			eat();
			return tokenizer.nextToken();
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		public boolean hasNext() {
			eat();
			return (tokenizer != null && tokenizer.hasMoreElements());
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}
	}
}

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


import java.util.Scanner ;
public class Main {

	public static void main(String[] args) {
	Scanner stdin = new Scanner( System.in ) ;
	int a,b,c;
	a = stdin.nextInt();
	b = stdin.nextInt();
	c = stdin.nextInt();
	if(a<=c){
		if(c<=b){
			System.out.println("Yes");
		}else{
			System.out.println("No");
		}
	}else{
		System.out.println("No");

		}
	}

}

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


import java.util.*;
import java.io.PrintWriter;
import static java.lang.Integer.*;
import static java.lang.Long.*;
import static java.lang.Math.*;
import static java.lang.System.*;

public class Main {
	public static void main(String[] args) {
		int i,j;
		Scanner sc = new Scanner(in);
		int n = parseInt(sc.next());
		int m = parseInt(sc.next());
		int[] c = new int[n+1];
		int a;
		int b;
		for (i = 0; i < m; i++) {
			a = parseInt(sc.next());
			b = parseInt(sc.next());
			c[a]++;
			c[b]++;
		}
		sc.close();
		PrintWriter pw = new PrintWriter(out);
		for(i=1;i<=n;i++) {
			pw.println(c[i]);
		}
		pw.flush();
	}
}

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

8 8
1 2
3 4
1 5
2 8
3 7
5 2
4 1
6 8

Sample Output 3

3
3
2
2
2
1
1
2


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

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Integer city=Integer.valueOf(sc.nextLine().split(" ")[0]);
		int[] road=new int[city];

		while (sc.hasNextLine()) {
			Integer[] roadInfo=Arrays.asList(sc.nextLine().split(" "))
					.stream()
					.map(Integer::valueOf)
					.toArray(Integer[]::new);
			road[roadInfo[0]-1]++;
			road[roadInfo[1]-1]++;
		}
		for(Integer i:road) {
			System.out.println(i);
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[][] nums = new int[n][2];
        for (int i = 0; i < n; i++) {
            nums[i][0] = sc.nextInt();
            nums[i][1] = sc.nextInt();
        }

        Arrays.sort(nums, (a, b) -> Integer.compare(a[1], b[1]));
        Arrays.sort(nums, (a, b) -> Integer.compare(a[0], b[0]));

        int count = 0;
        for (int i = 0; i < n; i++) {
            count += nums[i][1];

            if (count >= k) {
                System.out.println(nums[i][0]);
                return;
            }

        }
    }
}

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    private static java.util.Scanner scanner = new java.util.Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt(), k = scanner.nextInt();
        IntStream.range(0, n)
                .boxed()
                .collect(Collectors.toMap(i -> scanner.nextInt(), i -> scanner.nextLong(), Long::sum, TreeMap::new))
                .entrySet().stream()
                .reduce((long)k, (rem, entry) -> {
                    if (rem != null && (rem -= entry.getValue()) <= 0) {
                        System.out.println(entry.getKey());
                        return null;
                    }
                    return rem;
                }, Long::sum);
    }
}


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

public class Main {

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

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

			int n = in.nextInt();
			int k = in.nextInt();
			long[] array = new long[100010];
			for (int i = 0; i < n; i++) {
				int a = in.nextInt();
				long b = in.nextLong();
				array[a] += b;
			}

			while (k > 0) {
				for (int i = 1; i < array.length; i++) {
					k -= array[i];
					if (k <= 0) {
						out.print(i);
						return;
					}
				}
			}

		}

	}

	static class ArrayUtils {
		public static Map<Integer, Integer> getCountMap(int[] array) {
			Map<Integer, Integer> map = new TreeMap<>();
			for (int x : array)
				map.merge(x, 1, Integer::sum);
			return map;
		}

	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

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

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

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

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

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

	}

}


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main{

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

		SortedSet<Long> set = new TreeSet<>();
		Map<Long, Long> map = new HashMap<>();
		for(int i = 0; i < n; i++){
			long a = scan.nextInt();
			long b = scan.nextInt();
			set.add(a);
			if(map.containsKey(a)){
				map.put(a, map.get(a) + b);
			}else{
				map.put(a, b);
			}
		}

		for(Iterator it = set.iterator();;){
			long num = (long) it.next();
			k -= map.get(num);
			if(k <= 0){
				System.out.println(num);
				break;
			}
		}

	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.Character.Subset;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.temporal.ValueRange;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ForkJoinPool;

import static java.util.Comparator.*;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        MyInput in = new MyInput(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        Solver solver = new Solver(in, out);
        solver.solve();

        out.close();
    }

    // ======================================================================
    static class Solver {
    	MyInput in;
    	PrintWriter out;
        public Solver(MyInput in, PrintWriter out) {
        	this.in = in;
        	this.out = out;
        }

        // -----------------------------------------
        // ベルマン・フォード
        long INF = 1000000000L * 2010;
        int N, M;
        int[] A, B, C;
        long[] dist;									// 最短距離
        public void solve() {
        	N = ni();
        	dist = new long[N];
        	Arrays.fill(dist, INF);						// INF で埋める
        	dist[0] = 0L;								// 始点を　０　で初期化する
        	M = ni();
        	A = new int[M];
        	B = new int[M];
        	C = new int[M];
        	for (int i = 0; i < M; i++) {
				A[i] = ni()-1;
				B[i] = ni()-1;
				C[i] = -ni();							// 正負を反転する（最大値を求めるので）
			}
        	long sv = 0L;
        	for (int i = 0; i < N; i++) {				// 頂点数繰り返す
        		for (int j = 0; j < M; j++) {			// 辺の数、最短距離を更新する
					if(dist[A[j]] == INF)	continue;
					if(dist[B[j]] > dist[A[j]] + C[j])
						dist[B[j]] = dist[A[j]] + C[j];	// 最短距離を更新する
				}
        		if(i == N - 2) {
        			sv = dist[N-1];						// 終点の値を保存する
        		}
			}
        	if(sv != dist[N-1])		prn("inf");			// 一回多く回して変化したらなら、負の閉路がある
        	else					prn(-sv);			// 最大値を出力する
        }

        // -----------------------------------------
        // Integer のキーに対して、カウントを管理する（カウントを足したり、引いたりする）
        static class MapCounter {
        	private Map<Long, Long> map = new TreeMap<>();
        	public MapCounter() {}
        	// キーのカウントに値を足す
        	public void add(long key) {
        		add(key, 1);
        	}
           	public void add(long key, int cnt) {
        		Long val = map.get(key);
        		if(val == null) {
        			map.put(key, (long)cnt);
        		} else {
        			map.put(key,  val + cnt);
        		}
        	}
           	// キーのカウントから値を引く
        	public void sub(long key) {
        		sub(key, 1);
        	}
        	public void sub(long key, int cnt) {
        		Long val = map.get(key);
        		if(val == null) {
        			map.put(key, (long)-cnt);
        		} else {
        			map.put(key,  val - cnt);
        		}
        	}
        	// キーのカウントを取得する（なければ　ＮＵＬＬを返す）
        	public Long getCountwithNull(long key) {
        		return map.get(key);
        	}
        	// キーのカウントを取得する（なければ　０　を返す）
        	public Long getCount(long key) {
        		Long val = map.get(key);
        		if(val == null)		return 0L;
        		else 				return val;
        	}
        	public Set<Long> getKey() {
        		return map.keySet();
        	}
        	// 登録されているキーの数を返す
        	public int getKeyCount() {
        		return map.keySet().size();
        	}
        }
        // -----------------------------------------
        // 配列のバイナリーサーチ　１
        boolean isRightMin(int[] a, boolean f, int index, int key) {
    	    if (f && a[index] >= key)		return true;		// 以上
    	    else if (!f && a[index] > key)	return true;		// より大きい
    	    else 							return false;
    	}
    	// 配列 a の中で key 以上（f=true)または、より大きく（f=false)、一番小さい値を返す
    	int binarySearchRightMin(int[] a, boolean f, int key) {
    	    int ng = -1; 				//「index = 0」が条件を満たすこともあるので、初期値は -1
    	    int ok = (int)a.length; 	// 「index = a.length-1」が条件を満たさないこともあるので、初期値は a.length()

    	    /* ok と ng のどちらが大きいかわからないことを考慮 */
    	    while (Math.abs(ok - ng) > 1) {
    	        int mid = (ok + ng) / 2;

    	        if (isRightMin(a, f, mid, key))	ok = mid;	// 下半分を対象とする
    	        else 							ng = mid;	// 上半分を対象とする
    	    }
    	    return ok;		// ←　ここで返すのは　isOK() が true の時にセットする方（ok / ng)
    	}
        // -----------------------------------------
        // 配列のバイナリーサーチ　２
        boolean isLeftMax(int[] a, boolean f, int index, int key) {
    	    if (f && a[index] <= key)		return true;		// 以下
    	    else if (!f && a[index] < key)	return true;		// より小さい
    	    else 							return false;
    	}
    	// 配列 a の中で key 以下（f=true)または、より小さい（f=false)、一番大きい値を返す
    	int binarySearchLeftMax(int[] a, boolean f, int key) {
    	    int ng = -1; 				//「index = 0」が条件を満たすこともあるので、初期値は -1
    	    int ok = (int)a.length; 	// 「index = a.length-1」が条件を満たさないこともあるので、初期値は a.length()

    	    /* ok と ng のどちらが大きいかわからないことを考慮 */
    	    while (Math.abs(ok - ng) > 1) {
    	        int mid = (ok + ng) / 2;

    	        if (isLeftMax(a, f, mid, key))	ng = mid;	// 上半分を対象とする
    	        else 							ok = mid;	// 下半分を対象とする
    	    }
    	    return ng;		// ←　ここで返すのは　isOK() が true の時にセットする方（ok / ng)
    	}

        // -----------------------------------------
    	// オイラーツアー（部分木対応）　　　→　　工事中
    	static class EulerTour {
    		Graph g;
    		List<Integer> euler_tour = new ArrayList<>();
    		int[] begin, end;
    		int k = 0, root = 0;

    		void dfs(int v,int p, PrintWriter out) {
    			out.println("v = " + v + "  p = " + p);
    			begin[v] = k;
    			euler_tour.add(v);
    			k++;
    			if(!g.contains(v)) {
    				return;
    			}
    			for(int i : g.get(v)) {
    				if(i != p) {
    					dfs(i, v, out);
    					euler_tour.add(v);
    					k++;
    				}
    			}
    			end[v]=k;
    		}
    		// 初期化
    		public void init(int p_cnt, int root, Graph g, PrintWriter out) {
    			begin = new int[p_cnt + 1];
    			end = new int[p_cnt + 1];
    			this.root = root;
    			this.g = g;
    			dfs(root, -1, out);
    		}
    		// 部分木の頂点を渡すと、オイラーツアーの部分木を返す
    		public List getPartTour(int v) {
    			return euler_tour.subList(begin[v], end[v]);
    		}
    		// 部分木の頂点を渡すと、頂点のリストを返す
    		public List<Integer> getPartList(int v) {
    			Set<Integer> set = new TreeSet<>();
				set.addAll(getPartTour(v));
				List<Integer> ans = new ArrayList<>();
				for(Integer p : set) {
					ans.add(p);
				}
				return ans;
    		}
    	}

        // -----------------------------------------
        // 重みなし　グラフのリンクリスト
        static class Graph {
        	// 頂点に紐づく頂点のリスト
            private Map<Integer, List<Integer>> data = new HashMap<Integer, List<Integer>>();
//            // 全ての頂点のセット
//            private Set<Integer> point = new TreeSet<>();
            // 頂点と頂点の繋がりを追加する
            void add(int from, int to) {
            	List<Integer> list = data.get(from);
            	if(list == null) {
            		list = new ArrayList<Integer>();
            		data.put(from, list);
            	}
            	list.add(to);
//            	point.add(key);
//            	point.add(value);
            }
            // 指定された頂点に紐づく、頂点のリストを返す
            List<Integer> get(int key) {
            	return data.get(key);
            }
            // 頂点 key が登録されているか？
            boolean contains(int key) {
            	return data.containsKey(key);
            }

            //　頂点のセットを返す
            Set<Integer> keySet() {
            	return data.keySet();
            }
            // 頂点　key_1 と 頂点　key_2 がつながっていれば　true を返す
            boolean isConnect(int key_1, int key_2) {
            	List<Integer> list = data.get(key_1);
            	if(list == null)	return false;
            	else 				return list.contains(key_2);
            }
            // 指定された頂点から、すべての頂点への距離を返す
            List<PP> distList(int key) {
            	List<PP> dist = new ArrayList<>();		// 頂点と距離のペアのリスト
            	Set<Integer> mark = new HashSet<>();	// 処理したら入れる
    			Stack<PP> stack = new Stack<>();		// スタックの宣言
    			stack.push(new PP(key, 0));				// スタートをスタックに保存
    			while(!stack.isEmpty()) {
    				PP wk = stack.pop();				// スタックから次の頂点を取得
    				int pp = wk.getKey();
    				int dd = wk.getVal();
    				mark.add(pp);						// 通過マーク
        			dist.add(new PP(pp, dd));			// 距離を登録
    				List<Integer> list = get(pp);		// つながっている頂点のリストを取得
    				for(int next : list) {
    					if(mark.contains(next))	continue;
    					stack.push(new PP(next, dd + 1));
    				}
    			}
    			return dist;
            }
            // ダンプ
            void dump(PrintWriter out) {
            	for(int key : data.keySet()) {
            		out.print(key + " : ");
            		for(int val : data.get(key)) {
            			out.print(val + " ");
            		}
            		out.println("");
            	}
            }
        }
        // -----------------------------------------
        // 重さを持ったグラフのリンクリスト
        static class GraphWith {
        	// キーに紐づくリストに、頂点番号と重さのペアを持つ
            private Map<Integer, List<PP>> data = new HashMap<Integer, List<PP>>();
            // 指定された頂点に紐づく、頂点と重さのペアを追加する
            void add(int key, PP p) {
            	List<PP> list = data.get(key);
            	if(list == null) {
            		list = new ArrayList<PP>();
            		data.put(key, list);
            	}
            	list.add(p);
            }
            // 頂点に紐づく、頂点と重さのペアのリストを返す
            List<PP> get(int key) {
            	return data.get(key);
            }
            // 頂点 key が登録されているか？
            boolean contains(int key) {
            	return data.containsKey(key);
            }

            //　頂点のセットを返す
            Set<Integer> keySet() {
            	return data.keySet();
            }
            // 頂点　key_1 と 頂点　key_2 がつながっていれば　true を返す
            boolean isConnect(int key_1, int key_2) {
            	List<PP> list = data.get(key_1);
            	if(list == null)	return false;
            	boolean ans = false;
            	for(PP p : list) {
            		if(p.getKey() == key_2) {
            			ans = true;
            			break;
            		}
            	}
            	return ans;
            }
        }
        // -----------------------------------------
        // 重みなし　グラフのリンクリスト(Long)
        static class GraphLong {
            private Map<Long, List<Long>> G = new HashMap<Long, List<Long>>();
            void add(long key, long value) {
            	List<Long> list = G.get(key);
            	if(list == null) {
            		list = new ArrayList<Long>();
            		G.put(key, list);
            	}
            	list.add(value);
            }
            List<Long> get(long key) {
            	return G.get(key);
            }
        }
        // -----------------------------------------
        // 重さを持ったグラフのリンクリスト(Long)
        static class GraphLongWith {
            private Map<Long, List<PPL>> G = new HashMap<Long, List<PPL>>();
            void add(long key, PPL p) {
            	List<PPL> list = G.get(key);
            	if(list == null) {
            		list = new ArrayList<PPL>();
            		G.put(key, list);
            	}
            	list.add(p);
            }
            List<PPL> get(long key) {
            	return G.get(key);
            }
        }
        // -----------------------------------------

        void prn(String s) {
        	out.println(s);
        }
        void prn(int i) {
        	out.println(i);
        }
        void prn(long i) {
        	out.println(i);
        }
        void prr(String s) {
        	out.print(s);
        }
        int ni() {
        	return in.nextInt();
        }
        long nl() {
        	return in.nextLong();
        }
        double nd() {
        	return in.nextDouble();
        }
        String ns() {
        	return in.nextString();
        }
        int[] ndi(int n) {
        	int[] ans = new int[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = ni();
        	}
        	return ans;
        }
        long[] ndl(int n) {
        	long[] ans = new long[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = nl();
        	}
        	return ans;
        }
        double[] ndd(int n) {
        	double[] ans = new double[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = nd();
        	}
        	return ans;
        }
        String[] nds(int n) {
        	String[] ans = new String[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = ns();
        	}
        	return ans;
        }
        int[][] nddi(int n, int m) {
        	int[][] ans = new int[n][m];
        	for(int i=0; i < n; i++) {
            	for(int j=0; j < m; j++) {
            		ans[i][j] = ni();
            	}
        	}
        	return ans;
        }
        long[][] nddl(int n, int m) {
        	long[][] ans = new long[n][m];
        	for(int i=0; i < n; i++) {
            	for(int j=0; j < m; j++) {
            		ans[i][j] = nl();
            	}
        	}
        	return ans;
        }
    }
    // Set に入れるなら　PPKEY　を使う！
    static class PP{
    	public int key, val;
    	public PP(int key, int val) {
    		this.key = key;
    		this.val = val;
    	}
		public int getKey() {
			return key;
		}
		public void setKey(int key) {
			this.key = key;
		}
		public int getVal() {
			return val;
		}
		public void setVal(int val) {
			this.val = val;
		}
    }
    static class PPL {
    	public long key, val;
    	public PPL(long key, long val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public void setKey(long key) {
			this.key = key;
		}
		public long getVal() {
			return val;
		}
		public void setVal(long val) {
			this.val = val;
		}
    }
    static class PPDL {
    	public long key;
    	public long[] val;
    	public PPDL(long key, long[] val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public void setKey(long key) {
			this.key = key;
		}
		public long[] getVal() {
			return val;
		}
		public void setVal(long[] val) {
			this.val = val;
		}
		public void dump(PrintWriter out) {
			out.print("key = " + key + "  val ");
			for(int i=0; i < val.length; i++) {
				out.print("[" + val[i] + "] ");
			}
			out.println("");
		}
    }
    // HashMap のキーに使う　→　Set に入れるのもこれ（PPでは値での比較が行われない）
    static final class PPKEY{
    	private final int key, val;
    	public PPKEY(int key, int val) {
    		this.key = key;
    		this.val = val;
    	}
		public int getKey() {
			return key;
		}
		public int getVal() {
			return val;
		}
	    @Override
	    public boolean equals(Object obj) {
	        if (obj instanceof PPKEY) {
	        	PPKEY dest = (PPKEY) obj;
	            return this.key == dest.key && this.val == dest.val;
	        } else {
	            return false;
	        }
	    }
	    @Override
	    public int hashCode() {
	        return Objects.hash(key, val);
	    }
    }
    // HashMap のキーに使う　→　Set に入れるのもこれ（PPでは値での比較が行われない）
    static final class PPLKEY{
    	private final long key, val;
    	public PPLKEY(long key, long val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public long getVal() {
			return val;
		}
	    @Override
	    public boolean equals(Object obj) {
	        if (obj instanceof PPKEY) {
	        	PPKEY dest = (PPKEY) obj;
	            return this.key == dest.key && this.val == dest.val;
	        } else {
	            return false;
	        }
	    }
	    @Override
	    public int hashCode() {
	        return Objects.hash(key, val);
	    }
    }
    // ======================================================================
    static class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {
        /** serialVersionUID. */
        private static final long serialVersionUID = 6411527075103472113L;

        public Pair(final K key, final V value) {
            super(key, value);
        }
     }
    static class MyInput {
        private final BufferedReader in;
        private static int pos;
        private static int readLen;
        private static final char[] buffer = new char[1024 * 8];
        private static char[] str = new char[500 * 8 * 2];
        private static boolean[] isDigit = new boolean[256];
        private static boolean[] isSpace = new boolean[256];
        private static boolean[] isLineSep = new boolean[256];

        static {
            for (int i = 0; i < 10; i++) {
                isDigit['0' + i] = true;
            }
            isDigit['-'] = true;
            isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
            isLineSep['\r'] = isLineSep['\n'] = true;
        }

        public MyInput(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
        }

        public int read() {
            if (pos >= readLen) {
                pos = 0;
                try {
                    readLen = in.read(buffer);
                } catch (IOException e) {
                    throw new RuntimeException();
                }
                if (readLen <= 0) {
                    throw new MyInput.EndOfFileRuntimeException();
                }
            }
            return buffer[pos++];
        }

        public int nextInt() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            int ret = 0;
            if (str[0] == '-') {
                i = 1;
            }
            for (; i < len; i++) ret = ret * 10 + str[i] - '0';
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

        public long nextLong() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            long ret = 0L;
            if (str[0] == '-') {
                i = 1;
            }
            for (; i < len; i++) ret = ret * 10 + str[i] - '0';
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

        public double nextDouble() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            double ret = 0;
            if (str[0] == '-') {
                i = 1;
            }
            int cnt = 0;
            for (; i < len; i++) {
            	if(str[i] == '.') {
            		cnt = 10;
            		continue;
            	}
            	if(cnt == 0) {
            		ret = ret * 10 + str[i] - '0';
            	} else {
            		ret = ret + ((double)(str[i] - '0') / cnt);
            		cnt *= 10;
            	}
            }
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

       public String nextString() {
        	String ret = new String(nextDChar()).trim();
            return ret;
        }

        public char[] nextDChar() {
            int len = 0;
            len = reads(len, isSpace);
            char[] ret = new char[len + 1];
            for (int i=0; i < len; i++)		ret[i] = str[i];
            ret[len] = 0x00;
            return ret;
        }

        public char nextChar() {
            while (true) {
                final int c = read();
                if (!isSpace[c]) {
                    return (char) c;
                }
            }
        }

        int reads(int len, boolean[] accept) {
            try {
                while (true) {
                    final int c = read();
                    if (accept[c]) {
                        break;
                    }
                    if (str.length == len) {
                        char[] rep = new char[str.length * 3 / 2];
                        System.arraycopy(str, 0, rep, 0, str.length);
                        str = rep;
                    }
                    str[len++] = (char) c;
                }
            } catch (MyInput.EndOfFileRuntimeException e) {
            }
            return len;
        }

        static class EndOfFileRuntimeException extends RuntimeException {
        }
    }
}

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


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

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

		int h;
		int w;
		int k;

		String[][] map1;
		int[][] map2;

		int px = -1;
		int py = -1;

		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			String line;

			line = br.readLine();
			{
				String[] tokens = line.split(" ");
				h = Integer.parseInt(tokens[0]);
				w = Integer.parseInt(tokens[1]);
				k = Integer.parseInt(tokens[2]);
			}

			map1 = new String[h][w];
			map2 = new int[h][w];

			int r = 0;
			while ((line = br.readLine()) != null) {
				String[] tokens = line.split("");

				for (int i = 0; i < w; i++) {
					map1[r][i] = tokens[i + 1];
					map2[r][i] = Integer.MAX_VALUE;
					if (map1[r][i].equals("S")) {
						px = r;
						py = i;
					}
				}

				r++;
			}
		}

		map2[px][py] = 0;
		int count  = 0;

		Loop1:
		while(true) {
			for (int i = 0; i < h; i++) {
				for (int j = 0; j < w; j++) {
					//if (count == map2[i][j]) {
						for (int i2 = -k; i2 <= k; i2++) {
							for (int j2 = -k; Math.abs(j2) + Math.abs(i2) <= k; j2++) {
								if (i + i2 < h && j + j2 < w && 0 <= i + i2 && 0 <= j + j2 && ".".equals(map1[i + i2][j + j2])) {
									if (i + i2 == 0 || i + i2 == h - 1 ||
										j + j2 == 0 || j + j2 == w -1) {
										count++;
										break Loop1;
									}
									if (map2[i + i2][j + j2] > count + 1) {
										map2[i + i2][j + j2] = count + 1;
									}
								}
							}
						}
					//}
				}
			}

			count++;

			for (int i = 0; i < h; i++) {
				for (int j = 0; j < w; j++) {
					if (count == map2[i][j] || count - 1 == map2[i][j]) {
						for (int i2 = -k; i2 <= k; i2++) {
							for (int j2 = -k; Math.abs(j2) + Math.abs(i2) <= k; j2++) {
								if (i + i2 < h && j + j2 < w && 0 <= i + i2 && 0 <= j + j2 && "#".equals(map1[i + i2][j + j2])) {
									if ("#".equals(map1[i + i2][j + j2])) {
										map1[i + i2][j + j2] = ".";
									}
								}
							}
						}
					}
				}
			}
		}

		System.out.println(count);
	}
}

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


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

public class Main {
  private static String solve(int n, int[] a, int[] b) {
    ArrayList<ArrayList<Integer>> edges = new ArrayList<>();
    for (int i = 0; i <= n; i++) {
      edges.add(new ArrayList<>());
    }
    for (int i = 0; i < n - 1; i++) {
      edges.get(a[i]).add(b[i]);
      edges.get(b[i]).add(a[i]);
    }
    for (int i = 1; i <= n; i++) {
      int numLeaf = 0;
      for (int next : edges.get(i)) {
        if (edges.get(next).size() == 1) {
          numLeaf++;
        }
      }
      if (numLeaf >= 2) {
        return "First";
      }
    }
    return "Second";
  }

  private static void execute(ContestReader reader, PrintWriter out) {
    int n = reader.nextInt();
    int[] a = new int[n - 1];
    int[] b = new int[n - 1];
    for (int i = 0; i < n - 1; i++) {
      a[i] = reader.nextInt();
      b[i] = reader.nextInt();
    }
    out.println(solve(n, a, b));
  }

  public static void main(String[] args) {
    ContestReader reader = new ContestReader(System.in);
    PrintWriter out = new PrintWriter(System.out);
    execute(reader, out);
    out.flush();
  }
}

class ContestReader {
  private BufferedReader reader;
  private StringTokenizer tokenizer;

  ContestReader(InputStream in) {
    reader = new BufferedReader(new InputStreamReader(in));
  }

  public String next() {
    while (tokenizer == null || !tokenizer.hasMoreTokens()) {
      try {
        tokenizer = new java.util.StringTokenizer(reader.readLine());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    return tokenizer.nextToken();
  }

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

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

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

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

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

class Algorithm {
  private static void swap(Object[] list, int a, int b) {
    Object tmp = list[a];
    list[a] = list[b];
    list[b] = tmp;
  }

  public static <T extends Comparable<? super T>> boolean nextPermutation(T[] ts) {
    int rightMostAscendingOrderIndex = ts.length - 2;
    while (rightMostAscendingOrderIndex >= 0 &&
        ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostAscendingOrderIndex + 1]) >= 0) {
      rightMostAscendingOrderIndex--;
    }
    if (rightMostAscendingOrderIndex < 0) {
      return false;
    }

    int rightMostGreatorIndex = ts.length - 1;
    while (ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostGreatorIndex]) >= 0) {
      rightMostGreatorIndex--;
    }

    swap(ts, rightMostAscendingOrderIndex, rightMostGreatorIndex);
    for (int i = 0; i < (ts.length - rightMostAscendingOrderIndex - 1) / 2; i++) {
      swap(ts, rightMostAscendingOrderIndex + 1 + i, ts.length - 1 - i);
    }
    return true;
  }
}

Score : 900 points

Problem Statement

There is a tree with N vertices numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Initially, each vertex is uncolored.

Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:

Select a vertex that is not painted yet.

If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.

Then, after all the vertices are colored, the following procedure takes place:

Repaint every white vertex that is adjacent to a black vertex, in black.

Note that all such white vertices are repainted simultaneously, not one at a time.

If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins.
Determine the winner of the game, assuming that both persons play optimally.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

The input graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi wins; print Second if Aoki wins.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Below is a possible progress of the game:

First, Takahashi paint vertex 2 white.

Then, Aoki paint vertex 1 black.

Lastly, Takahashi paint vertex 3 white.

In this case, the colors of vertices 1, 2 and 3 after the final procedure are black, black and white, resulting in Takahashi's victory.

Sample Input 2

4
1 2
2 3
2 4

Sample Output 2

First

Sample Input 3

6
1 2
2 3
3 4
2 5
5 6

Sample Output 3

Second


import java.util.Scanner;

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

        long A;
        long B;
        long C;
        try (Scanner sc = new Scanner(System.in)) {
            A = sc.nextLong();
            B = sc.nextLong();
            C = sc.nextLong();
        }

        long AmB = A % B;

        for (int i = 0; i < B; i++) {
            if ((AmB * i) % B == C) {
                System.out.println("Yes");
                return;
            }
        }
        System.out.println("No");
    }
}

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


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

public class Main {

	public static void main(String[] args) {

		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int T = sc.nextInt();
		int[] t = new int[N];
		for (int i = 0; i < N; i++)
			t[i] = sc.nextInt();
		int ans = 0;
		for (int i = 0; i < N - 1; i++) {
			if (t[i + 1] - t[i] >= T)
				ans += T;
			else
				ans += t[i + 1] - t[i];
		}
		System.out.println(ans+T);

	}
	//以下、自作ライブラリ

	//最大公約数
	public static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);
		long c = 0;
		c = a % b;
		if (c == 0)
			return b;
		return gcd(b, c);
	}

	//最小公倍数
	public static long lcm(long m, long n) {
		return m * n / gcd(m, n);
	}

	//素数判定
	public static boolean isPrime(int n) {
		if (n < 2)
			return false;
		if (n == 2)
			return true;
		if (n % 2 == 0)
			return false;

		for (int i = 3; i * i <= n; i += 2) {
			if (n % i == 0)
				return false;
		}
		return true;
	}
}

//以下、高速スキャナークラス
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

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

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		String s1 = sc.next();
		String s2 = sc.next();
		String s3 = sc.next();
		sc.close();
		String str1 = s1.substring(0,1).toUpperCase();
		String str2 = s2.substring(0,1).toUpperCase();
		String str3 = s3.substring(0,1).toUpperCase();
		System.out.println(str1 + str2 + str3);
	}
}

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


import java.util.Scanner;

public class Main {

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

    public static void main(String[] args) {
	long X = Long.parseLong(scan.next());
	long Y = Long.parseLong(scan.next());

	System.out.println(Math.abs(X-Y) <= 1 ? "Brown" : "Alice");
	scan.close();
    }
}

Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


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

public class Main{

    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int a = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());
        if((a^b)==0){
            System.out.println("Alice");
        }else{
            System.out.println("Brown");
        }

    }

}


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Main main = new Main();
		main.solveC();
	}

	private void solveC() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int L = sc.nextInt();
		int T = sc.nextInt();
		int offset = L;
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < N; i++) {
			int x = sc.nextInt();
			int d = sc.nextInt();
			int g = x + T * (3 - d * 2);
			list.add(g);
			if (offset > g) {
				offset = g;
			}
		}
		List<Integer> relativeList = new ArrayList<Integer>();
		int index = 0;
		for (int x : list) {
			relativeList.add((x - offset) % L);
			if (x - offset >= L) {
				index += (x - offset) / L;
			}
		}
		Collections.sort(relativeList);
		index %= N;
		for (int x : relativeList.subList(index, N)) {
			System.out.println((((x + offset) % L) + L) % L);
		}
		for (int x : relativeList.subList(0, index)) {
			System.out.println((((x + offset) % L) + L) % L);
		}
	}
}

Score : 700 points

Problem Statement

There is a circle with a circumference of L.
Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point.
On this circumference, there are N ants.
These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coordinate X_i.

The N ants have just started walking.
For each ant i, you are given the initial direction W_i. Ant i is initially walking clockwise if W_i is 1; counterclockwise if W_i is 2.
Every ant walks at a constant speed of 1 per second.
Sometimes, two ants bump into each other.
Each of these two ants will then turn around and start walking in the opposite direction.

For each ant, find its position after T seconds.

Constraints

All input values are integers.

1 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq T \leq 10^9

0 \leq X_1 < X_2 < ... < X_N \leq L - 1

1 \leq W_i \leq 2

Input

The input is given from Standard Input in the following format:

N L T
X_1 W_1
X_2 W_2
:
X_N W_N

Output

Print N lines.
The i-th line should contain the coordinate of ant i after T seconds. Here, each coordinate must be between 0 and L-1, inclusive.

Sample Input 1

3 8 3
0 1
3 2
6 1

Sample Output 1

1
3
0

1.5 seconds after the ants start walking, ant 1 and 2 bump into each other at coordinate 1.5.
1 second after that, ant 1 and 3 bump into each other at coordinate 0.5.
0.5 seconds after that, that is, 3 seconds after the ants start walking, ants 1, 2 and 3 are at coordinates 1, 3 and 0, respectively.

Sample Input 2

4 20 9
7 2
9 1
12 1
18 1

Sample Output 2

7
18
18
1


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

class Main {

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

        try {

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

            String[] pillarHeightList = br.readLine().split(" ");
            int firstPillar = Integer.parseInt(pillarHeightList[0]);
            int secondPillar = Integer.parseInt(pillarHeightList[1]);
            int thirdPillar = Integer.parseInt(pillarHeightList[2]);

            String isPillarsBeautiful = "NO";

            if ((secondPillar - firstPillar) == (thirdPillar - secondPillar)) {
                isPillarsBeautiful = "YES";
            }

            System.out.println(isPillarsBeautiful);

        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (final Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.Character.Subset;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.temporal.ValueRange;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Comparator.*;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        MyInput in = new MyInput(inputStream);
        PrintWriter out = new PrintWriter(outputStream);

        Solver solver = new Solver(in, out);
        solver.solve();

        out.close();
    }

    // ======================================================================
    static class Solver {
    	MyInput in;
    	PrintWriter out;
        public Solver(MyInput in, PrintWriter out) {
        	this.in = in;
        	this.out = out;
        }

        // ======================================================================
        public void solve() {
            int a = ni();
            int b = ni();
            int c = ni();
            prn((b-a) == (c-b) ? "YES" : "NO");
        }
        // -----------------------------------------
        // Integer のキーに対して、カウントを管理する（カウントを足したり、引いたりする）
        static class MapCounter {
        	private Map<Integer, Long> map = new HashMap<>();
        	public MapCounter() {}
        	// キーのカウントに値を足す
        	public void add(int key) {
        		add(key, 1);
        	}
           	public void add(int key, int cnt) {
        		Long val = map.get(key);
        		if(val == null) {
        			map.put(key, (long)cnt);
        		} else {
        			map.put(key,  val + cnt);
        		}
        	}
           	// キーのカウントから値を引く
        	public void sub(int key) {
        		sub(key, 1);
        	}
        	public void sub(int key, int cnt) {
        		Long val = map.get(key);
        		if(val == null) {
        			map.put(key, (long)-cnt);
        		} else {
        			map.put(key,  val - cnt);
        		}
        	}
        	// キーのカウントを取得する（なければ　ＮＵＬＬを返す）
        	public Long getCountwithNull(int key) {
        		return map.get(key);
        	}
        	// キーのカウントを取得する（なければ　０　を返す）
        	public Long getCount(int key) {
        		Long val = map.get(key);
        		if(val == null)		return 0L;
        		else 				return val;
        	}
        	public Set<Integer> getKey() {
        		return map.keySet();
        	}
        	// 登録されているキーの数を返す
        	public int getKeyCount() {
        		return map.keySet().size();
        	}
        }
        // -----------------------------------------
        // 配列のバイナリーサーチ　１
        boolean isRightMin(int[] a, boolean f, int index, int key) {
    	    if (f && a[index] >= key)		return true;		// 以上
    	    else if (!f && a[index] > key)	return true;		// より大きい
    	    else 							return false;
    	}
    	// 配列 a の中で key 以上（f=true)または、より大きく（f=false)、一番小さい値を返す
    	int binarySearchRightMin(int[] a, boolean f, int key) {
    	    int ng = -1; 				//「index = 0」が条件を満たすこともあるので、初期値は -1
    	    int ok = (int)a.length; 	// 「index = a.length-1」が条件を満たさないこともあるので、初期値は a.length()

    	    /* ok と ng のどちらが大きいかわからないことを考慮 */
    	    while (Math.abs(ok - ng) > 1) {
    	        int mid = (ok + ng) / 2;

    	        if (isRightMin(a, f, mid, key))	ok = mid;	// 下半分を対象とする
    	        else 							ng = mid;	// 上半分を対象とする
    	    }
    	    return ok;		// ←　ここで返すのは　isOK() が true の時にセットする方（ok / ng)
    	}
        // -----------------------------------------
        // 配列のバイナリーサーチ　２
        boolean isLeftMax(int[] a, boolean f, int index, int key) {
    	    if (f && a[index] <= key)		return true;		// 以下
    	    else if (!f && a[index] < key)	return true;		// より小さい
    	    else 							return false;
    	}
    	// 配列 a の中で key 以下（f=true)または、より小さい（f=false)、一番大きい値を返す
    	int binarySearchLeftMax(int[] a, boolean f, int key) {
    	    int ng = -1; 				//「index = 0」が条件を満たすこともあるので、初期値は -1
    	    int ok = (int)a.length; 	// 「index = a.length-1」が条件を満たさないこともあるので、初期値は a.length()

    	    /* ok と ng のどちらが大きいかわからないことを考慮 */
    	    while (Math.abs(ok - ng) > 1) {
    	        int mid = (ok + ng) / 2;

    	        if (isLeftMax(a, f, mid, key))	ng = mid;	// 上半分を対象とする
    	        else 							ok = mid;	// 下半分を対象とする
    	    }
    	    return ng;		// ←　ここで返すのは　isOK() が true の時にセットする方（ok / ng)
    	}

        // -----------------------------------------
    	// オイラーツアー（部分木対応）
    	static class EulerTour {
    		Graph g;
    		List<Integer> euler_tour = new ArrayList<>();
    		int[] begin, end;
    		int k = 0, root = 0;

    		void dfs(int v,int p, PrintWriter out) {
    			out.println("v = " + v + "  p = " + p);
    			begin[v] = k;
    			euler_tour.add(v);
    			k++;
    			if(!g.contains(v)) {
    				return;
    			}
    			for(int i : g.get(v)) {
    				if(i != p) {
    					dfs(i, v, out);
    					euler_tour.add(v);
    					k++;
    				}
    			}
    			end[v]=k;
    		}
    		// 初期化
    		public void init(int p_cnt, int root, Graph g, PrintWriter out) {
    			begin = new int[p_cnt + 1];
    			end = new int[p_cnt + 1];
    			this.root = root;
    			this.g = g;
    			dfs(root, -1, out);
    		}
    		// 部分木の頂点を渡すと、オイラーツアーの部分木を返す
    		public List getPartTour(int v) {
    			return euler_tour.subList(begin[v], end[v]);
    		}
    		// 部分木の頂点を渡すと、頂点のリストを返す
    		public List<Integer> getPartList(int v) {
    			Set<Integer> set = new TreeSet<>();
				set.addAll(getPartTour(v));
				List<Integer> ans = new ArrayList<>();
				for(Integer p : set) {
					ans.add(p);
				}
				return ans;
    		}
    	}

        // -----------------------------------------
        // グラフのリンクリスト
        static class Graph {
        	// 頂点に紐づく頂点のリスト
            private Map<Integer, List<Integer>> data = new HashMap<Integer, List<Integer>>();
//            // 全ての頂点のセット
//            private Set<Integer> point = new TreeSet<>();
            // 頂点と頂点の繋がりを追加する
            void add(int from, int to) {
            	List<Integer> list = data.get(from);
            	if(list == null) {
            		list = new ArrayList<Integer>();
            		data.put(from, list);
            	}
            	list.add(to);
//            	point.add(key);
//            	point.add(value);
            }
            // 指定された頂点に紐づく、頂点のリストを返す
            List<Integer> get(int key) {
            	return data.get(key);
            }
            // 頂点 key が登録されているか？
            boolean contains(int key) {
            	return data.containsKey(key);
            }

            //　頂点のセットを返す
            Set<Integer> keySet() {
            	return data.keySet();
            }
            // 頂点　key_1 と 頂点　key_2 がつながっていれば　true を返す
            boolean isConnect(int key_1, int key_2) {
            	List<Integer> list = data.get(key_1);
            	if(list == null)	return false;
            	else 				return list.contains(key_2);
            }
            // 指定された頂点から、すべての頂点への距離を返す
            List<PP> distList(int key) {
            	List<PP> dist = new ArrayList<>();		// 頂点と距離のペアのリスト
            	Set<Integer> mark = new HashSet<>();	// 処理したら入れる
    			Stack<PP> stack = new Stack<>();		// スタックの宣言
    			stack.push(new PP(key, 0));				// スタートをスタックに保存
    			while(!stack.isEmpty()) {
    				PP wk = stack.pop();				// スタックから次の頂点を取得
    				int pp = wk.getKey();
    				int dd = wk.getVal();
    				mark.add(pp);						// 通過マーク
        			dist.add(new PP(pp, dd));			// 距離を登録
    				List<Integer> list = get(pp);		// つながっている頂点のリストを取得
    				for(int next : list) {
    					if(mark.contains(next))	continue;
    					stack.push(new PP(next, dd + 1));
    				}
    			}
    			return dist;
            }
            // ダンプ
            void dump(PrintWriter out) {
            	for(int key : data.keySet()) {
            		out.print(key + " : ");
            		for(int val : data.get(key)) {
            			out.print(val + " ");
            		}
            		out.println("");
            	}
            }
        }
        // -----------------------------------------
        // 重さを持ったグラフのリンクリスト
        static class GraphWith {
        	// キーに紐づくリストに、頂点番号と重さのペアを持つ
            private Map<Integer, List<PP>> data = new HashMap<Integer, List<PP>>();
            // 指定された頂点に紐づく、頂点と重さのペアを追加する
            void add(int key, PP p) {
            	List<PP> list = data.get(key);
            	if(list == null) {
            		list = new ArrayList<PP>();
            		data.put(key, list);
            	}
            	list.add(p);
            }
            // 頂点に紐づく、頂点と重さのペアのリストを返す
            List<PP> get(int key) {
            	return data.get(key);
            }
            // グラフの存在チェック（重さは関係しない）
            // 頂点　key と 頂点　value がつながっていれば　true を返す
            boolean contains(int key, int value) {
            	List<PP> list = data.get(key);
            	if(list == null)	return false;
            	boolean ans = false;
            	for(PP p : list) {
            		if(p.getKey() == value) {
            			ans = true;
            			break;
            		}
            	}
            	return ans;
            }
        }
        // -----------------------------------------
        // グラフのリンクリスト(Long)
        static class GraphLong {
            private Map<Long, List<Long>> G = new HashMap<Long, List<Long>>();
            void add(long key, long value) {
            	List<Long> list = G.get(key);
            	if(list == null) {
            		list = new ArrayList<Long>();
            		G.put(key, list);
            	}
            	list.add(value);
            }
            List<Long> get(long key) {
            	return G.get(key);
            }
        }
        // -----------------------------------------
        // 重さを持ったグラフのリンクリスト(Long)
        static class GraphLongWith {
            private Map<Long, List<PPL>> G = new HashMap<Long, List<PPL>>();
            void add(long key, PPL p) {
            	List<PPL> list = G.get(key);
            	if(list == null) {
            		list = new ArrayList<PPL>();
            		G.put(key, list);
            	}
            	list.add(p);
            }
            List<PPL> get(long key) {
            	return G.get(key);
            }
        }
        // -----------------------------------------

        void prn(String s) {
        	out.println(s);
        }
        void prn(int i) {
        	out.println(i);
        }
        void prn(long i) {
        	out.println(i);
        }
        void prr(String s) {
        	out.print(s);
        }
        int ni() {
        	return in.nextInt();
        }
        long nl() {
        	return in.nextLong();
        }
        double nd() {
        	return in.nextDouble();
        }
        String ns() {
        	return in.nextString();
        }
        int[] ndi(int n) {
        	int[] ans = new int[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = ni();
        	}
        	return ans;
        }
        long[] ndl(int n) {
        	long[] ans = new long[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = nl();
        	}
        	return ans;
        }
        double[] ndd(int n) {
        	double[] ans = new double[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = nd();
        	}
        	return ans;
        }
        String[] nds(int n) {
        	String[] ans = new String[n];
        	for(int i=0; i < n; i++) {
        		ans[i] = ns();
        	}
        	return ans;
        }
        int[][] nddi(int n, int m) {
        	int[][] ans = new int[n][m];
        	for(int i=0; i < n; i++) {
            	for(int j=0; j < m; j++) {
            		ans[i][j] = ni();
            	}
        	}
        	return ans;
        }
        long[][] nddl(int n, int m) {
        	long[][] ans = new long[n][m];
        	for(int i=0; i < n; i++) {
            	for(int j=0; j < m; j++) {
            		ans[i][j] = nl();
            	}
        	}
        	return ans;
        }
    }
    static class PP{
    	public int key, val;
    	public PP(int key, int val) {
    		this.key = key;
    		this.val = val;
    	}
		public int getKey() {
			return key;
		}
		public void setKey(int key) {
			this.key = key;
		}
		public int getVal() {
			return val;
		}
		public void setVal(int val) {
			this.val = val;
		}
    }
    static class PPL {
    	public long key, val;
    	public PPL(long key, long val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public void setKey(long key) {
			this.key = key;
		}
		public long getVal() {
			return val;
		}
		public void setVal(long val) {
			this.val = val;
		}
    }
    static class PPDL {
    	public long key;
    	public long[] val;
    	public PPDL(long key, long[] val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public void setKey(long key) {
			this.key = key;
		}
		public long[] getVal() {
			return val;
		}
		public void setVal(long[] val) {
			this.val = val;
		}
		public void dump(PrintWriter out) {
			out.print("key = " + key + "  val ");
			for(int i=0; i < val.length; i++) {
				out.print("[" + val[i] + "] ");
			}
			out.println("");
		}
    }
    // HashMap のキーに使う
    static final class PPKEY{
    	private final int key, val;
    	public PPKEY(int key, int val) {
    		this.key = key;
    		this.val = val;
    	}
		public int getKey() {
			return key;
		}
		public int getVal() {
			return val;
		}
	    @Override
	    public boolean equals(Object obj) {
	        if (obj instanceof PPKEY) {
	        	PPKEY dest = (PPKEY) obj;
	            return this.key == dest.key && this.val == dest.val;
	        } else {
	            return false;
	        }
	    }
	    @Override
	    public int hashCode() {
	        return Objects.hash(key, val);
	    }
    }
    // HashMap のキーに使う
    static final class PPLKEY{
    	private final long key, val;
    	public PPLKEY(long key, long val) {
    		this.key = key;
    		this.val = val;
    	}
		public long getKey() {
			return key;
		}
		public long getVal() {
			return val;
		}
	    @Override
	    public boolean equals(Object obj) {
	        if (obj instanceof PPKEY) {
	        	PPKEY dest = (PPKEY) obj;
	            return this.key == dest.key && this.val == dest.val;
	        } else {
	            return false;
	        }
	    }
	    @Override
	    public int hashCode() {
	        return Objects.hash(key, val);
	    }
    }
    // ======================================================================
    static class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {
        /** serialVersionUID. */
        private static final long serialVersionUID = 6411527075103472113L;

        public Pair(final K key, final V value) {
            super(key, value);
        }
     }
    static class MyInput {
        private final BufferedReader in;
        private static int pos;
        private static int readLen;
        private static final char[] buffer = new char[1024 * 8];
        private static char[] str = new char[500 * 8 * 2];
        private static boolean[] isDigit = new boolean[256];
        private static boolean[] isSpace = new boolean[256];
        private static boolean[] isLineSep = new boolean[256];

        static {
            for (int i = 0; i < 10; i++) {
                isDigit['0' + i] = true;
            }
            isDigit['-'] = true;
            isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
            isLineSep['\r'] = isLineSep['\n'] = true;
        }

        public MyInput(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
        }

        public int read() {
            if (pos >= readLen) {
                pos = 0;
                try {
                    readLen = in.read(buffer);
                } catch (IOException e) {
                    throw new RuntimeException();
                }
                if (readLen <= 0) {
                    throw new MyInput.EndOfFileRuntimeException();
                }
            }
            return buffer[pos++];
        }

        public int nextInt() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            int ret = 0;
            if (str[0] == '-') {
                i = 1;
            }
            for (; i < len; i++) ret = ret * 10 + str[i] - '0';
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

        public long nextLong() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            long ret = 0L;
            if (str[0] == '-') {
                i = 1;
            }
            for (; i < len; i++) ret = ret * 10 + str[i] - '0';
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

        public double nextDouble() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            double ret = 0;
            if (str[0] == '-') {
                i = 1;
            }
            int cnt = 0;
            for (; i < len; i++) {
            	if(str[i] == '.') {
            		cnt = 10;
            		continue;
            	}
            	if(cnt == 0) {
            		ret = ret * 10 + str[i] - '0';
            	} else {
            		ret = ret + ((double)(str[i] - '0') / cnt);
            		cnt *= 10;
            	}
            }
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

       public String nextString() {
        	String ret = new String(nextDChar()).trim();
            return ret;
        }

        public char[] nextDChar() {
            int len = 0;
            len = reads(len, isSpace);
            char[] ret = new char[len + 1];
            for (int i=0; i < len; i++)		ret[i] = str[i];
            ret[len] = 0x00;
            return ret;
        }

        public char nextChar() {
            while (true) {
                final int c = read();
                if (!isSpace[c]) {
                    return (char) c;
                }
            }
        }

        int reads(int len, boolean[] accept) {
            try {
                while (true) {
                    final int c = read();
                    if (accept[c]) {
                        break;
                    }
                    if (str.length == len) {
                        char[] rep = new char[str.length * 3 / 2];
                        System.arraycopy(str, 0, rep, 0, str.length);
                        str = rep;
                    }
                    str[len++] = (char) c;
                }
            } catch (MyInput.EndOfFileRuntimeException e) {
            }
            return len;
        }

        static class EndOfFileRuntimeException extends RuntimeException {
        }
    }
}


import java.util.Scanner;

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

	String kisupas = scan.nextLine();
	String gusupas = scan.nextLine();

	String[] kisu = kisupas.split("", 0);
	String[] gusu = gusupas.split("", 0);

	for(int i=0; i<kisu.length; i++){
	System.out.print(kisu[i]);
	if(i != gusu.length)
	System.out.print(gusu[i]);
	}
	}

}

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


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

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

    static class TaskB {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            String o = in.nextLine();
            String e = in.nextLine();
            String password = "";

            int size = Math.max(o.length(), e.length());

            for (int i = 0; i < size; ++i) {
                if (i < o.length()) {
                    password += String.valueOf(o.charAt(i));
                }

                if (i < e.length()) {
                    password += String.valueOf(e.charAt(i));
                }
            }

            out.println(password);
        }

    }
}


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

public class Main {
    static InputStream is;
    static PrintWriter out;
    static String INPUT = "";

    static void solve() {
        int N = ni();
        int[] as = new int[N * 3];

        for (int i = 0; i < N * 3; i++) {
            as[i] = ni();
        }

        Arrays.sort(as);

        long sum = 0;
        for (int i = N * 3 - 1 - N; i >= N; i--) {
            sum += as[i];
        }

        System.out.println(sum);
    }

    public static void main(String[] args) throws Exception {
        long S = System.currentTimeMillis();
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        out = new PrintWriter(System.out);

        solve();
        out.flush();
        long G = System.currentTimeMillis();
        tr(G-S+"ms");
    }

    private static boolean eof() {
        if(lenbuf == -1)return true;
        int lptr = ptrbuf;
        while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;

        try {
            is.mark(1000);
            while(true){
                int b = is.read();
                if(b == -1){
                    is.reset();
                    return true;
                }else if(!isSpaceChar(b)){
                    is.reset();
                    return false;
                }
            }
        } catch (IOException e) {
            return true;
        }
    }

    private static byte[] inbuf = new byte[1024];
    static int lenbuf = 0, ptrbuf = 0;

    private static int readByte() {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }

    private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private static double nd() { return Double.parseDouble(ns()); }
    private static char nc() { return (char)skip(); }

    private static String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private static char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private static char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private static int[] na(int n) {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private static int ni() {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private static long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


import java.util.*;

public class Main {

	private void doit(){
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			int n = sc.nextInt();
			int [] data = new int[n * 3];
			for(int i = 0; i < n * 3; i++){
				data[i] = sc.nextInt();
			}
			Arrays.sort(data);
			long sum = 0;
			for(int i = n; i < n * 3;i+=2){
				sum += data[i];
			}
			System.out.println(sum);
		}
	}

	private void debug(Object... o) {
		System.out.println("debug = " + Arrays.deepToString(o));
	}

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

}


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

class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine(), " ");
    int A = Integer.parseInt(st.nextToken());
    int B = Integer.parseInt(st.nextToken());
    int ans = (A + B) % 24;
    System.out.println(ans);
  }
}

Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


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();
              if(a+b>=24){
              System.out.println(a+b-24);
              }else{
              System.out.println(a+b);
              }
       }
}


import java.util.*;

public class Main{

  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
  	int n=sc.nextInt(),m=sc.nextInt(),e=0;
    long[] a=new long[n],b=new long[n],c=new long[m],d=new long[m];
    long min=1000000000;
    for(int i=0;i<n;i++){
      a[i]=sc.nextLong();
      b[i]=sc.nextLong();
    }
    for(int j=0;j<m;j++){
      c[j]=sc.nextLong();
      d[j]=sc.nextLong();
    }
    for(int i=0;i<n;i++){
      for(int j=0;j<m;j++){
        long f=Math.abs(a[i]-c[j])+Math.abs(b[i]-d[j]);
        if(min>f){
          e=j+1;
          min=f;
        }
      }
      System.out.println(e);
    }
  }
}

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

3 4
10 10
-10 -10
3 3
1 2
2 3
3 5
3 5

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int[][] ab = new int[n][2];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < 2; j++){
                ab[i][j] = scan.nextInt();
            }
        }
        int[][] cd = new int[m][2];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < 2; j++){
                cd[i][j] = scan.nextInt();
            }
        }
        int min = Integer.MAX_VALUE;
        int out = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(Math.abs(ab[i][0] - cd[j][0]) + Math.abs(ab[i][1] - cd[j][1]) < min){
                    min = Math.abs(ab[i][0] - cd[j][0]) + Math.abs(ab[i][1] - cd[j][1]);
                    out = j + 1;
                }
            }
            System.out.println(out);
            min = Integer.MAX_VALUE;
            out = 0;
        }
    }
}


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

public class Main
{

	static final int X = 0;
	static final int Y = 1;

	public static void main(String[] args) throws IOException
	{
		// TODO 自動生成されたメソッド・スタブ
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		int N = Integer.parseInt(str.substring(0, str.indexOf(" ")));
		int M = Integer.parseInt(str.substring(str.indexOf(" ") + 1));
		int Students[][] = new int[N][2];
		int CheckPoints[][] = new int[M][2];
		int Lan[][] = new int[N][2];
		for(int i = 0; i < N; i++)
		{
			str = br.readLine();
			Students[i][X] = Integer.parseInt(str.substring(0, str.indexOf(" ")));
			Students[i][Y] = Integer.parseInt(str.substring(str.indexOf(" ") + 1));
			Lan[i][0] = 1000000000;
			Lan[i][1] = 0;
		}
		for(int i = 0; i < M; i++)
		{
			str = br.readLine();
			CheckPoints[i][X] = Integer.parseInt(str.substring(0, str.indexOf(" ")));
			CheckPoints[i][Y] = Integer.parseInt(str.substring(str.indexOf(" ") + 1));
		}
		for(int i = 0; i < N; i++)
		{
			for(int j = 0; j < M; j++)
			{
				if(Lan[i][0] > Math.abs(Students[i][X] - CheckPoints[j][X]) + Math.abs(Students[i][Y] - CheckPoints[j][Y]))
				{
					Lan[i][0] = Math.abs(Students[i][X] - CheckPoints[j][X]) + Math.abs(Students[i][Y] - CheckPoints[j][Y]);
					Lan[i][1] = j + 1;
				}
			}
		}
		for(int i = 0; i < N; i++)
		{
			System.out.println(Lan[i][1]);
		}
	}

}