import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

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

	static void solve()
	{
		// 123
		// 122
		// 112
		// 113
		// 121
		// 111

		int n = ni();
		int[] b = na(n);
		for(int i = 0;i < n;i++){
			if(b[i] > i+1){
				out.println(-1);
				return;
			}
		}
		int[] c = new int[n];
		for(int i = 0;i < n;i++){
			c[i] = b[i]-1;
			for(int j = 0;j < i;j++){
				if(c[j] >= c[i]){
					c[j]++;
				}
			}
		}
		tr(c);
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				if(c[j] == i){
					int small = 1;
					for(int k = 0;k < j;k++){
						if(c[k] < c[j])small++;
					}
					out.println(small);
					break;
				}
			}
		}
	}

	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 boolean isSpaceChar(int c) { return !(c >= 32 && 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 : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


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

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();

		int matrix[][] = new int[n + 1][n + 1];

		for(int i = 0; i <= n; i++){
			Arrays.fill(matrix[i], 1);
		}

		for(int i = 0; i < (n + 1) / 2; i++){
			if(n % 2 == 1){
				matrix[i + 1][n - i - 1] = 0;
			}
			else{
				matrix[i + 1][n - i] = 0;
			}
		}

		for(int i = 1; i <= n; i++){
			for(int j = i + 1; j <= n; j++){
				if(matrix[i][j] != 0){
					System.out.println(i+" "+j);
				}
			}
		}
	}
}

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

Score : 700 points

Problem Statement

You are given an integer N.
Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:

The graph is simple and connected.

There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.

It can be proved that at least one such graph exists under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.

The output will be judged correct if the graph satisfies the conditions.

Sample Input 1

3

Sample Output 1

2
1 3
2 3

For every vertex, the sum of the indices of the vertices adjacent to that vertex is 3.

Submitted source-code file size, in bytes.

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

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


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int H = sc.nextInt();
		int W = sc.nextInt();
		int h = sc.nextInt();
		int w = sc.nextInt();

		System.out.println((H-h) * (W - w));
		sc.close();

	}

}

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


package min;

import java.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner sca=new Scanner(System.in);
		int a=sca.nextInt();
		int b=sca.nextInt();
		int y=sca.nextInt();
		int x=sca.nextInt();
		int v=a*b-y*b-(a-y)*x;
		System.out.print(v);
	}

}


import java.util.*;

public class Main
{
  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int m = in.nextInt();
    int[] l = new int[m];
    int[] r = new int[m];
    for (int i = m-1; i >= 0; i--)
    {
      l[i] = in.nextInt();
      r[i] = in.nextInt();
    }

    int[] size = new int[n];
    Arrays.fill(size, 1);
    long[] ans = new long[m];
    DSU d = new DSU(n);
    for (int i = 0; i < m; i++)
    	if (d.find(l[i]) != d.find(r[i]))
        {
          int a = size[d.find(l[i])];
          int b = size[d.find(r[i])];
          ans[m-1-i] = a*b;
          d.union(l[i], r[i]);
          size[d.find(l[i])] = a+b;
        }
    for (int i = 1; i < m; i++)
    {
      ans[i] += ans[i-1];
      System.out.println(ans[i]);
    }

    in.close();
  }

  public static class DSU
    {
        int[] set;

        DSU(int n)
        {
            Arrays.fill(set = new int[n], -1);
        }

        int find(int i)
        {
            return set[i] < 0 ? i : (set[i] = find(set[i]));
        }

        boolean union(int a, int b)
        {
            if ((a = find(a)) == (b = find(b))) return false;
            if (set[a] == set[b]) set[a]--;
            if (set[a] <= set[b]) set[b] = a; else set[a] = b;
            return true;
        }
    }
}

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String S = sc.next();
    DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    LocalDate reiwa = LocalDate.of(2019, 5, 1);

    LocalDate d = LocalDate.parse(S, sdf);
    if (d.isBefore(reiwa)) {
      System.out.println("Heisei");
    } else {
      System.out.println("TBD");
    }
  }
}

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Closeable;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.io.InputStream;

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

    static class CSyntheticKadomatsu {
        int N = 0;
        int A = 0;
        int B = 0;
        int C = 0;
        int[] l = null;
        final int INF = 1 << 29;

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            N = in.nextInt();
            A = in.nextInt();
            B = in.nextInt();
            C = in.nextInt();
            l = in.nextIntArray(N);
            int ans = dfs(0, 0, 0, 0);
            out.println(ans);
        }

        int dfs(int i, int a, int b, int c) {
            if (i == N) {
                if (a > 0 && b > 0 && c > 0) {
                    // 最初の1本に対して合成魔法のコストを払う必要はないのでここで引いておく(※)
                    return Math.abs(a - A) + Math.abs(b - B) + Math.abs(c - C) - 30;
                    // 無に対して延長魔法は使えないのでa,b,cどれにも+l[i]しなかったパターンにはINFを入れる
                } else {
                    return INF;
                }
            }
            int ret0 = dfs(i + 1, a, b, c);
            // ※ここでは最初の1本に対しても合成魔法のコストを払っている
            int ret1 = dfs(i + 1, a + l[i], b, c) + 10;
            int ret2 = dfs(i + 1, a, b + l[i], c) + 10;
            int ret3 = dfs(i + 1, a, b, c + l[i]) + 10;
            return Math.min(ret0, Math.min(ret1, Math.min(ret2, ret3)));
        }

    }

    static class FastScanner implements Closeable {
        private final InputStream in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;

        public FastScanner(InputStream in) {
            this.in = in;
        }

        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 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 int[] nextIntArray(final int n) {
            final int[] res = new int[n];
            for (int i = 0; i < n; i++) {
                res[i] = nextInt();
            }
            return res;
        }

        public void close() {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {

	public static void main(String[] args) {
		MyScanner sc = new MyScanner();
		int a=sc.nextInt();
		int b=sc.nextInt();
		int q=sc.nextInt();
		long s[]=new long[a];
		long t[]=new long[b];
		long ans[]=new long[q];
		for (int i = 0; i < a; i++) {
			s[i]=sc.nextLong();
		}
		for (int i = 0; i < b; i++) {
			t[i]=sc.nextLong();
		}

		long x[]=new long[q];
		for (int i = 0; i < q; i++) {
			x[i]=sc.nextLong();
		}

		int sn[]=new int[q];
		int tn[]=new int[q];
		for (int i = 0; i < q; i++) {
			sn[i]=nib(s,x[i],0,a-1);
			tn[i]=nib(t,s[sn[i]],0,b-1);
			ans[i]=Math.abs(s[sn[i]]-t[tn[i]])+Math.min(Math.abs(s[sn[i]]-x[i]),Math.abs(t[tn[i]]-x[i]));

			tn[i]=nib(t,x[i],0,b-1);
			sn[i]=nib(s,t[tn[i]],0,a-1);

			ans[i]=Math.min(ans[i],ans[i]=Math.abs(s[sn[i]]-t[tn[i]])+Math.min(Math.abs(s[sn[i]]-x[i]),Math.abs(t[tn[i]]-x[i])));

		}

		for (int i = 0; i < q; i++) {
			System.out.println(ans[i]);
		}

	}
	static int nib(long[] a,long x,int l,int r) {
		int an=0;

		if(l==r) {
			an=l;
		}else if(x<a[l]) {
			an=l;
		}else if(a[r]<x) {
			an=r;
		}
		else if(a[l]<x&&x<a[r]) {
			if(r-l==1) {
				if(Math.abs(a[l]-x)<Math.abs(a[r]-x)) {
					an=l;

				}else {
					an=r;
				}

			}else {
				if(nib(a,x,l,(l+r)/2)!=-1) {
					an=nib(a,x,l,(l+r)/2);
				}else {
					an=nib(a,x,(l+r)/2+1,r);
				}

			}
		}else {
			an=-1;
		}

		return an;
	}

//----------------------------------------------------------
	static int l_min(int[] a) {
		Arrays.sort(a);
		return a[0];
	}
	static int l_max(int[] a) {
		int l=a.length;
		Arrays.sort(a);
		return a[l-1];
	}

	public static PrintWriter out;

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

	}

}

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


import java.util.*;

public class Main{
	public static void main(String args[]){
    	Scanner sc = new Scanner(System.in);
        int a = Integer.parseInt(sc.next());
        int b = Integer.parseInt(sc.next());
        if(b%a == 0){
        	System.out.println(a+b);
        }else{
        	System.out.println(b-a);
        }
    }
}

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


import java.awt.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] a = new int[n];
        int[] b = new int[n];

        PriorityQueue<Point> que = new PriorityQueue<>((k, l) -> l.y - k.y);

        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            b[i] = sc.nextInt();
            que.add(new Point(i, a[i] + b[i]));
        }

        boolean t = true;

        long ts = 0;
        long as = 0;

        while (!que.isEmpty()) {
            if (t) {
                ts += a[que.poll().x];
            } else {
                as += b[que.poll().x];
            }
            t = !t;
        }

        System.out.println(ts - as);
    }
}

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.


import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

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

		final int N = sc.nextInt();
		sc.nextLine();
		final Map<Integer, Long> A = new HashMap<>();
		final Map<Integer, Long> B = new HashMap<>();
		final boolean[] selected = new boolean[N];

		for (int i = 0; i < N; i++) {
			final String line = sc.nextLine();
			final String[] split = line.split(" ");
			final long prefA = Long.parseLong(split[0]);
			final long prefB = Long.parseLong(split[1]);

			A.put(i, prefA);
			B.put(i, prefB);
			selected[i] = false;
		}

		List<Map.Entry<Integer, Long>> sortedA = A.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(new ValueComparator()))
				.collect(Collectors.toCollection(LinkedList::new));

		List<Map.Entry<Integer, Long>> sortedB = B.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(new ValueComparator()))
				.collect(Collectors.toCollection(LinkedList::new));

		long takahashi = 0;
		long aoki = 0;

		int numTrials = 0;
		while (numTrials < N) {
			boolean t = (numTrials % 2) == 0;

			Map.Entry<Integer, Long> maxT = getHighest(N, sortedA, selected);
			Map.Entry<Integer, Long> nextT = getSecondHighest(N, sortedA, selected);
			long prefMaxT = maxT.getValue();
			long prefNextT = (nextT == null) ? 0 : nextT.getValue();
			long expT = prefMaxT - prefNextT;

			Map.Entry<Integer, Long> maxA = getHighest(N, sortedB, selected);
			Map.Entry<Integer, Long> nextA = getSecondHighest(N, sortedB, selected);
			long prefMaxA = maxA.getValue();
			long prefNextA = (nextA == null) ? 0 : nextA.getValue();
			long expA = prefMaxA - prefNextA;

			if (t) {
				if (expT > expA) {
					takahashi += prefMaxT;
					selected[maxT.getKey()] = true;
				} else {
					final int key = maxA.getKey();
					takahashi += A.get(key);
					selected[key] = true;
				}
			} else {
				if (expA > expT) {
					aoki += prefMaxA;
					selected[maxA.getKey()] = true;
				} else {
					final int key = maxT.getKey();
					aoki += B.get(key);
					selected[key] = true;
				}
			}

			numTrials++;
		}

		System.out.println(takahashi - aoki);
	}

	private static Map.Entry<Integer, Long> getHighest(int N, List<Map.Entry<Integer, Long>> prefs, boolean[] selected) {
		for (int i = 0; i < N; i++) {
			final Map.Entry<Integer, Long> e = prefs.get(i);
			final boolean sel = selected[e.getKey()];

			if (!sel) {
				return e;
			}
		}

		return null;
	}

	private static Map.Entry<Integer, Long> getSecondHighest(int N, List<Map.Entry<Integer, Long>> prefs, boolean[] selected) {
		boolean firstFound = false;
		for (int i = 0; i < N; i++) {
			final Map.Entry<Integer, Long> e = prefs.get(i);
			final boolean sel = selected[e.getKey()];

			if (!sel) {
				if (firstFound) {
					return e;
				} else {
					firstFound = true;
				}
			}
		}

		return null;
	}

}

class ValueComparator implements Comparator<Long> {

	@Override
	public int compare(Long o1, Long o2) {
		return Long.compare(o2, o1);
	}

}


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

public class Main {
    public static void main(String args[]) {
        try (Scanner in = new Scanner(System.in)) {
            int N = in.nextInt();
            long[] A = new long[N];
            long[] B = new long[N];
            ArrayList<A> As = new ArrayList<>();
            for (int i = 0; i < N; i++) {
                A[i] = in.nextInt();
                B[i] = in.nextInt();
                As.add(new A(A[i], B[i], i));
            }
            Collections.sort(As, new Comparator<A>() {
                @Override
                public int compare(A o1, A o2) {
                    if (o1.a - o1.b < o2.a - o2.b) {
                        return -1;
                    }
                    if (o1.a - o1.b > o2.a - o2.b) {
                        return 1;
                    }
                    if (o1.a < o2.a) {
                        return 1;
                    }
                    if (o1.a > o2.a) {
                        return -1;
                    }
                    if (o1.b < o2.b) {
                        return -1;
                    }
                    if (o1.b > o2.b) {
                        return 1;
                    }
                    return 0;
                }
            });

            long sum = 0;
            for (int i = 0; i < N; i++) {
                if (i % 2 == 0) {
                    sum += As.get(i).a;
                } else {
                    sum -= As.get(i).b;
                }
//                Utils.debug(i, sum, As.get(i).a, As.get(i).b, As.get(i).i);
            }

            System.out.println(sum);
        }
    }
}

class A {
    long a;
    long b;
    int i;

    public A(long a, long b, int i) {
        super();
        this.a = a;
        this.b = b;
        this.i = i;
    }
}


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

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		ArrayList<U> aa = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			int a = in.nextInt();
			int b = in.nextInt();

			U u = new U();
			u.d = a - b;
			u.t = a + b;
            u.a = a;

			aa.add(u);
		}
		Collections.sort(aa, (u1, u2) -> u1.d - u2.d);
		long r = 0;
		for (int i = 0; i < aa.size(); i = i + 2) {
			r += aa.get(i).a;
		}

		in.close();
		System.out.println(r);
	}

}

class U {
	int d;
	long t;
	int a;
}


import java.util.*;
import java.util.stream.*;

class Main{
	static Scanner s=new Scanner(System.in);

	static class D{
		public D(int a,int b){
			this.a=a;
			this.b=b;
		}
		int a,b;
	}
	public static void main(String[] $){
		int n=s.nextInt(),m=s.nextInt();
		ArrayList<Set<Integer>>to=new ArrayList<>(n);
		ArrayList<Set<Integer>>from=new ArrayList<>(n);
		for(int i=0;i<n;++i) {
			to.add(new HashSet<>());
			from.add(new HashSet<>());
		}

		for(int e=n+m-1;e>0;--e) {
			int f=s.nextInt()-1;
			int t=s.nextInt()-1;
			to.get(f).add(t);
			from.get(t).add(f);
		}

		int root=IntStream.range(0,n).filter(i->from.get(i).isEmpty()).findAny().getAsInt();
		System.err.println(root);

		int[]parent=new int[n];

		ArrayDeque<Long>q=new ArrayDeque<>();
		for(int i:to.get(root)) {
			q.add((long)root*n+i);
		}
		while(!q.isEmpty()) {
			for(int _q=q.size();_q>0;--_q) {
				long p=q.poll();
				int pf=(int)p/n;
				int pt=(int)p%n;
				to.get(pf).remove(pt);
				from.get(pt).remove(pf);
				if(from.get(pt).isEmpty())
					parent[pt]=pf+1;

				for(int i:to.get(pt)) {
					q.add((long)pt*n+i);
				}
			}
		}
		Arrays.stream(parent).forEach(System.out::println);
	}
}

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


import java.util.Scanner;

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

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


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

		// 出力
		System.out.println(sc.nextInt() * sc.nextInt() / 2);
	}
}


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.math.BigDecimal;
import java.text.DecimalFormat;
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.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 AB = ni();
			int BC = ni();
			int CA = ni();
			prn(AB * BC / 2);
        }

        // -----------------------------------------
        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 Graph {
        private Map<Integer, List<Integer>> data = new HashMap<Integer, List<Integer>>();
        void add(int key, int value) {
        	List<Integer> list = data.get(key);
        	if(list == null) {
        		list = new ArrayList<Integer>();
        		data.put(key, list);
        	}
        	list.add(value);
        }
        List<Integer> get(int key) {
        	return data.get(key);
        }
        Set<Integer> keySet() {
        	return data.keySet();
        }
        boolean contains(int key, int value) {
        	List<Integer> list = data.get(key);
        	if(list == null)	return false;
        	else 				return list.contains(value);
        }
        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);
        }
        // グラフの存在チェック（重さは関係しない）
        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);
        }
    }

    // ======================================================================
    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 sc = new Scanner(System.in);
        int s = sc.nextInt();
        int pre = s;
        boolean con = true;
        int ans = 1;
        boolean[] c = new boolean[1000000];
        while(con){
            ans++;
            int b;
            if(pre %2 == 0){
                b = pre /2;
            }else{
                b = 3 * pre +1;
            }
            if(c[b]) break;
            else {
                c[b] = true;
                pre = b;
            }
        }

        System.out.println(ans);
        sc.close();
    }

}

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


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

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int s = sc.nextInt();
		Set<Integer> sSet = new HashSet<Integer>();

		while(!sSet.contains(s)) {
			sSet.add(s);

			if(s % 2 == 0) {
				s = s/2;
			} else {
				s = 3*s + 1;
			}
		}

		System.out.println(sSet.size() + 1);

	}

}


import java.util.*;

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

	class P{
		int d;
		int k;
		P(int d, int k){
			this.d=d;
			this.k=k;
		}
	}

	public void run() {
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		int k=sc.nextInt();

		ArrayList<ArrayList<Integer>> ll = new ArrayList<>();
		for(int i=0; i<n; i++) {
			ll.add(new ArrayList<Integer>());
		}
		for(int i=0; i<n; i++) {
			int t = sc.nextInt();
			int d = sc.nextInt();
			ll.get(--t).add(d);
		}
		for(ArrayList<Integer> l : ll) {
			Collections.sort(l);
		}

		ArrayList<P> pl = new ArrayList<P>();
		for(ArrayList<Integer> l : ll) {
			for(int i=0; i<l.size(); i++) {
				int d = l.get(i);
				P p = new P(d, (i==l.size()-1) ? 1 : 0);
				pl.add(p);
			}
		}
		Collections.sort(pl, (p1, p2)->Integer.compare(p1.d, p2.d));

		int choose = 0;
		long sum = 0;
		long max = 0;
		int kind = 0;
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		for(int i=pl.size()-1; i>=0; i--) {
			int d = pl.get(i).d;
			sum += d;
			kind += pl.get(i).k;
			choose++;
			if( pl.get(i).k==0) {
				pq.add(d);
			}
			if(choose > k) {
				choose--;
				if(pq.isEmpty()) break;
				sum -= pq.poll();
			}
			if(choose == k) {
				max = Math.max(max, sum + (long)kind*kind);
			}

		}
		System.out.println(max);
		sc.close();
	}

}

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

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

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

Note that the output may not fit into a 32-bit integer type.


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

import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;

public class Main{
    static final long mod=1000000007;
//    static int dx[]={-1,0,1,0};
//    static int dy[]={0,-1,0,1};

    public  static void main(String[] args)   throws Exception, IOException{
        Reader sc = new Reader(System.in);
        PrintWriter out=new PrintWriter(System.out);
        // int n=sc.nextInt();
        // char c[][] = new char[h][w];
        // char c[]=sc.nextString().toCharArray();
        // int d[]=new int[n];
        // for(int i=0; i<n; i++) {d[i]=sc.nextInt();}

        int n=sc.nextInt();
        int k=sc.nextInt();
        P p[] = new P[n];
        for (int i = 0; i < p.length; i++) {
			p[i] = new P(sc.nextInt()-1, sc.nextInt());
		}
        sort(p);
        long s=0,v=0;
        int c=n-k+1,z=n-k+1;
        int u[]=new int[n];
        for (int i = 0; i < k; i++) {
			s+=p[n-i-1].d;
			if(0==u[p[n-i-1].id]) v++;
			u[p[n-i-1].id]++;
		}
        long ans=s+v*v;

        while(--c>=0 && ++v<=k) {
        	if(u[p[c].id]!=0)continue;
        	while(u[p[z].id]==0)z++;
        	u[p[z].id]--;
        	u[p[c].id]++;
        	s += -p[z].d + p[c].d + 2*v-1;
        	ans = max(ans,s);
        }

        out.println(ans);
        out.flush();
    }

    static boolean validpos(int x,int y,int r, int c){
        return x<r && 0<=x && y<c && 0<=y;
    }

    static void db(Object... os){
        System.err.println(Arrays.deepToString(os));
    }
}

//class P {
//    int id, d;
//    P(int  id, int d) {
//        this.id=id;
//        this.d=d;
//    }
//}

class P implements Comparable<P>{
    int id, d;
    P(int  id, int d) {
        this.id=id;
        this.d=d;
    }
    public int compareTo(P p){
        return d-p.d; //des
    }
}

class Reader
{
    private BufferedReader x;
    private StringTokenizer st;

    public Reader(InputStream in)
    {
        x = new BufferedReader(new InputStreamReader(in));
        st = null;
    }
    public String nextString() throws IOException
    {
        while( st==null || !st.hasMoreTokens() )
            st = new StringTokenizer(x.readLine());
        return st.nextToken();
    }
    public int nextInt() throws IOException
    {
        return Integer.parseInt(nextString());
    }
    public int[] nextIntArray(int size) throws IOException{
    	int r[] = new int[size];
    	for (int i = 0; i < size; i++) {
			r[i] = this.nextInt();
		}
    	return r;
    }
    public long nextLong() throws IOException
    {
        return Long.parseLong(nextString());
    }
    public double nextDouble() throws IOException
    {
        return Double.parseDouble(nextString());
    }
}


import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
    static class Reader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(s()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
    }

    //       |----|       /\      |    |   -----   |
    //       |   /       /  \     |    |     |     |
    //       |--/       /----\    |----|     |     |
    //       |   \     /      \   |    |     |     |
    //       |    \   /        \  |    |   -----   -------

    public static void main(String[] args)throws IOException
    {
        PrintWriter out= new PrintWriter(System.out);
        Reader sc=new Reader();
        int arr[]=sc.arr(4);
        Arrays.sort(arr);
        if(arr[0]==1&&arr[1]==4&&arr[2]==7&&arr[3]==9)
        out.println("YES");
        else
        out.println("NO");
        out.flush();
    }
}

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


import java.util.Arrays;

class DisjointSet {
  public int[] upper;

  public DisjointSet(int n)
  {
      upper = new int[n];
      Arrays.fill(upper, -1);
  }

  public DisjointSet(DisjointSet ds)
  {
      this.upper = Arrays.copyOf(ds.upper, ds.upper.length);
  }

  public int root(int x)
  {
      return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
  }

  public boolean equiv(int x, int y)
  {
      return root(x) == root(y);
  }

  public boolean union(int x, int y)
  {
      x = root(x);
      y = root(y);
      if(x != y) {
          if(upper[y] < upper[x]) {
              int d = x; x = y; y = d;
          }
          upper[x] += upper[y];
          upper[y] = x;
      }
      return x == y;
  }

  public int count()
  {
      int ct = 0;
      for(int u : upper){
          if(u < 0)ct++;
      }
      return ct;
  }
}

class SegmentTreeRMQPos {
  public int M, H, N;
  public long[] st;
  public int[] pos;

  public SegmentTreeRMQPos(long[] a)
  {
      N = a.length;
      M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
      H = M>>>1;
      st = new long[M];
      pos = new int[M];
      for(int i = 0;i < N;i++){
          st[H+i] = a[i];
          pos[H+i] = i;
      }
      Arrays.fill(st, H+N, M, Long.MAX_VALUE);
      for(int i = H-1;i >= 1;i--)propagate(i);
  }

  public void update(int pos, int x)
  {
      st[H+pos] = x;
      for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i);
  }

  private void propagate(int i)
  {
      if(st[2*i] <= st[2*i+1]){
          st[i] = st[2*i];
          pos[i] = pos[2*i];
      }else{
          st[i] = st[2*i+1];
          pos[i] = pos[2*i+1];
      }
  }

  public int minpos;
  public long minval;

  public long min(int l, int r){
      minpos = -1;
      minval = Long.MAX_VALUE;
      min(l, r, 0, H, 1);
      return minval;
  }

  private void min(int l, int r, int cl, int cr, int cur)
  {
      if(l <= cl && cr <= r){
          if(st[cur] < minval){
              minval = st[cur];
              minpos = pos[cur];
          }
      }else{
          int mid = cl+cr>>>1;
          if(cl < r && l < mid)min(l, r, cl, mid, 2*cur);
          if(mid < r && l < cr)min(l, r, mid, cr, 2*cur+1);
      }
  }
}

public class Main {
  private static void solve() {
    int n = ni();
    long d = ni();
    long[] a = nal(n);

    long[] left = new long[n];
    long[] right = new long[n];
    for (int i = 0; i < n; i ++) {
      left[i] = -i * d + a[i];
      right[i] = i * d + a[i];
    }

    long[][] table = new long[n][3];
    for (int i = 0; i < n; i ++) {
      table[i][0] = i;
      table[i][1] = a[i];
    }
    Arrays.sort(table, (o1, o2) -> Long.compare(o2[1], o1[1]));
    int[] idx = Arrays.stream(table).mapToInt(v -> (int)v[0]).toArray();

    SegmentTreeRMQPos stL = new SegmentTreeRMQPos(left);
    SegmentTreeRMQPos stR = new SegmentTreeRMQPos(right);

    int[] from = new int[n * 3];
    int[] to = new int[n * 3];
    long[] w = new long[n * 3];
    int ptr = 0;
    for (int i : idx) {
      stL.min(0, i);
      stR.min(i + 1, n);

      if (stL.minpos >= 0) {
        from[ptr] = i;
        to[ptr] = stL.minpos;
        w[ptr] = i * d + a[i] + stL.minval;
        ptr ++;
      }
      if (stR.minpos >= 0) {
        from[ptr] = i;
        to[ptr] = stR.minpos;
        w[ptr] = -i * d + a[i] + stR.minval;
        ptr ++;
      }
    }
    long ret = kruskal(from, to, w, ptr, n);
    System.out.println(ret);
  }

  public static long kruskal(int[] one, int[] other, long[] w, int m, int n)
  {
      DisjointSet ds = new DisjointSet(n);
      int p = m;
      long[] ord = new long[p];
      for(int i = 0;i < p;i++)ord[i] = (long)w[i]<<32 | i;
      Arrays.sort(ord);

      long d = 0;
      for(int i = 0;i < m;i++){
          int cur = (int)ord[i];
          if(!ds.equiv(one[cur], other[cur])){
              ds.union(one[cur], other[cur]);
              d += w[cur];
          }
      }

      return d;
  }

  public static void main(String[] args) {
    new Thread(null, new Runnable() {
      @Override
      public void run() {
        long start = System.currentTimeMillis();
        String debug = args.length > 0 ? args[0] : null;
        if (debug != null) {
          try {
            is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
        reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
        solve();
        out.flush();
        tr((System.currentTimeMillis() - start) + "ms");
      }
    }, "", 64000000).start();
  }

  private static java.io.InputStream is = System.in;
  private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
  private static java.util.StringTokenizer tokenizer = null;
  private static java.io.BufferedReader reader;

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

  private static double nd() {
    return Double.parseDouble(next());
  }

  private static long nl() {
    return Long.parseLong(next());
  }

  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 char[] ns() {
    return next().toCharArray();
  }

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

  private static int[][] ntable(int n, int m) {
    int[][] table = new int[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        table[i][j] = ni();
      }
    }
    return table;
  }

  private static int[][] nlist(int n, int m) {
    int[][] table = new int[m][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        table[j][i] = ni();
      }
    }
    return table;
  }

  private static int ni() {
    return Integer.parseInt(next());
  }

  private static void tr(Object... o) {
    if (is != System.in)
      System.out.println(java.util.Arrays.deepToString(o));
  }
}

Score : 600 points

Problem Statement

There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}.
Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.

Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}.
For Takahashi, find the minimum possible total cost to achieve the objective.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq D \leq 10^9

1 \leq A_{i} \leq 10^9

A_{i} and D are integers.

Input

Input is given from Standard Input in the following format:

N D
A_1 A_2 ... A_N

Output

Print the minimum possible total cost.

Sample Input 1

3 1
1 100 1

Sample Output 1

106

This cost can be achieved by, for example, building roads connecting City 1, 2 and City 1, 3.

Sample Input 2

3 1000
1 100 1

Sample Output 2

2202

Sample Input 3

6 14
25 171 7 1 17 162

Sample Output 3

497

Sample Input 4

12 5
43 94 27 3 69 99 56 25 8 15 46 8

Sample Output 4

658


import java.util.Scanner;

public class Main
{
	static boolean[][] grid;
	static int h,w;
	static boolean[][] visited;
	static long[][] islandbw = new long[160000][2];
	static int curisland = 0;

	static void findIsland(int x, int y, boolean state, int island)
	{
		if(x<0||y<0||x>=w||y>=h)return;
		if(visited[x][y])return;
		if(grid[x][y] == state)
		{
			visited[x][y] = true;
//			System.out.println(x + " " + y + ": island " + island);
			if(grid[x][y])
				islandbw[island][0]++;
			else islandbw[island][1]++;

			//expand
			findIsland(x-1,y,!state,island);
			findIsland(x+1,y,!state,island);
			findIsland(x,y-1,!state,island);
			findIsland(x,y+1,!state,island);
		}
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		h = sc.nextInt();
		w = sc.nextInt();
		grid = new boolean[w][h];
		visited = new boolean[w][h];

		for(int y = 0; y < h; y++)
		{
			String s = sc.next();
			for(int x = 0; x < w; x++)
			{
				grid[x][y] = s.charAt(x)=='#';
			}
		}

		for(int y = 0; y < h; y++)
		{
			for(int x = 0; x < w; x++)
			{
				if(!visited[x][y])
				{
					findIsland(x,y,grid[x][y],curisland);
					curisland++;
				}
			}
		}

		long an = 0;
		for(int i = 0; i < curisland; i++)
		{
			an += (islandbw[i][0] * islandbw[i][1]);
		}

		System.out.println(an);

	}

}

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


import java.util.*;
import java.awt.*;
import java.awt.geom.*;
import static java.lang.System.*;
import static java.lang.Math.*;
public class Main {
    public static void main(String[] $) {
        Scanner sc = new Scanner(in);
        int h=sc.nextInt();
        int w=sc.nextInt();
        char[][] f=new char[h][w];
        for (int i = 0; i < h; i++) {
            String t=sc.next();
            for (int j = 0; j < w; j++) {
                f[i][j]=t.charAt(j);
            }
        }
        long ans=0;
        int[] dx={-1,0,1,0};
        int[] dy={0,-1,0,1};
        int[][] node=new int[h][w];
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if(node[i][j]==0) {
                    Queue<Point> q = new ArrayDeque<>();
                    if(f[i][j]=='#'){
                        q.add(new Point(i, j));
                        node[i][j]++;
                    }
                    long tempW = 0, tempB = 0;
                    while (!q.isEmpty()) {
                        Point p = q.poll();
                        if (f[p.x][p.y] == '.') tempW++;
                        else tempB++;
                        for (int k = 0; k < 4; k++) {
                            int x = p.x + dx[k];
                            int y = p.y + dy[k];
                            if (0 <= x && x < h && 0 <= y && y < w) {
                                if (node[x][y] == 0 && f[p.x][p.y] != f[x][y]) {
                                    q.add(new Point(x, y));
                                    node[x][y]++;
                                }
                            }
                        }
                    }
                    ans += tempB * tempW;
                }
            }
        }
        out.println(ans);
    }
}


import java.util.*;

public class Main
{
  static int n;
  static int[][] abc;
  static Integer[][] memo;
  public static void main(String[] args)
  {
	Scanner in = new Scanner(System.in);
    n = in.nextInt();
    abc = new int[3][n];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < 3; j++)
        abc[j][i] = in.nextInt();

    memo = new Integer[3][n];
    System.out.println(go());
    in.close();
  }

  public static int go()
  {
    int ans = 0;
    for (int i = 0; i < 3; i++)
      ans = Math.max(ans, abc[i][0]+dp(i, 1));
    return ans;
  }

  public static int dp(int bad, int at)
  {
	if (at == n)
      return 0;
    if (memo[bad][at] != null)
      return memo[bad][at];

    int ans = 0;
    int to1 = 3-at;
    int to2 = 0;
    if (to1 == 3)
    {
      to1 = 1;
      to2 = 2;
    }
    ans = Math.max(ans, abc[to1][at]+dp(to1, at+1));
    ans = Math.max(ans, abc[to2][at]+dp(to2, at+1));
    return memo[bad][at] = ans;
  }
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


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

public class Main{

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

    void run(){
      Scanner sc=new Scanner(System.in);
      int N=sc.nextInt();
      long W=sc.nextLong();
      long[] w=new long[N];
      int[] v=new int[N];
      for(int i=0;i<N;++i){
          w[i]=sc.nextLong();
          v[i]=sc.nextInt();
      }
      long[] dp=new long[100001];
      Arrays.fill(dp,1L<<60);
      dp[0]=0;
      for(int i=0;i<N;++i){
          for(int j=dp.length-v[i]-1;j>=0;--j){
    	      dp[j+v[i]]=Math.min(dp[j+v[i]],dp[j]+w[i]);
          }
      }
      long ans=0;
      for(int i=0;i<dp.length;++i){
          if(dp[i]<=W)ans=Math.max(ans,i);
      }
      System.out.println(ans);
    }
}

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


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

public class Main {
	final static int MOD = 1000000007;
	final static int intMax = 1000000000;
	final static int intMin = -1000000000;
	final static int[] dx = { 0, 0, -1, 1 };
	final static int[] dy = { -1, 1, 0, 0 };

	static int T;

	static class Reader {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public Reader() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public Reader(String file_name) throws IOException {
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException {
			byte[] buf = new byte[360]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1) {
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}

	static ArrayList<Integer>[] adj;

	public static void main(String[] args) throws Exception {
		Reader in = new Reader();
		int N = in.nextInt();
		int M = in.nextInt();
		adj = new ArrayList[N];
		for(int i = 0; i < N; ++i) {
			adj[i] = new ArrayList<Integer>();
		}
		for(int i = 0; i < M; ++i) {
			int x = in.nextInt() - 1;
			int y = in.nextInt() - 1;
			adj[x].add(y);
		}
		int[] dp = new int[N];
		boolean[] vis = new boolean[N];
		for(int i = 0; i < N; ++i) {
			if(vis[i]) continue;
			LinkedList<Integer> q = new LinkedList<Integer>();
			q.add(i);
			vis[i] = true;
			while(!q.isEmpty()) {
				int cur = q.poll();
				for(Integer j : adj[cur]) {
					if(dp[cur] + 1 > dp[j]) {
						q.add(j);
						dp[j] = dp[cur] + 1;
						vis[j] = true;
					}
				}
			}
		}
		int mx = 0;
		for(int i = 0; i < N; ++i) {
			mx = Math.max(mx, dp[i]);
		}
		System.out.println(mx);
		in.close();
	}
}

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

5 8
5 3
2 3
2 4
5 2
5 1
1 4
4 3
1 3

Sample Output 3

3

The red directed path in the following figure is one of the longest:


// Problem : G - Longest Path
// Contest : Educational DP Contest
// URL : https://atcoder.jp/contests/dp/tasks/dp_g
// Memory Limit : 1024 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

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

public class Main {

	public static void main(String[] args) throws Exception {
		FastReader scan = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		//PrintWriter out = new PrintWriter("file.out");
		Task solver = new Task();
		//int t = scan.nextInt();
		int t = 1;
		for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
		out.close();
	}

	static class Task {
		static final int inf = Integer.MAX_VALUE;
		public void solve(int testNumber, FastReader sc, PrintWriter pw) {
			int n = sc.nextInt();
			ArrayList<Integer>[] adjl1 = new ArrayList[n];
			ArrayList<Integer>[] adjl2 = new ArrayList[n];
			int m = sc.nextInt();
			for(int i=0;i<n;i++){
				adjl1[i]=new ArrayList<Integer>();
				adjl2[i] = new ArrayList<Integer>();
			}
			for(int i = 0;i < m;i++){
				int a = sc.nextInt()-1;
				int b = sc.nextInt()-1;
				adjl1[a].add(b);
				adjl2[b].add(a);
			}
			Queue<Integer> q = new LinkedList<Integer>();
			int[] freq = new int[n];
			for(int i = 0;i < n; i++){
				if(adjl1[i].size() == 0){
					q.add(i);
					freq[i]++;
				}
			}
			int bfs[] = new int[n];
			while(!q.isEmpty()){
				int t = q.poll();
				freq[t]--;
				if(freq[t]>0){
					continue;
				}
				for(int x : adjl2[t]){
					if(bfs[x]<bfs[t]+1){
						bfs[x]=bfs[t]+1;
						q.add(x);
						freq[x]++;
					}
				}
			}
			int max = 0;
			for(int x : bfs){
				max=Math.max(x,max);
			}
			pw.println(max);
		}
	}
	long binpow(long a, long b, long m) {
		a %= m;
		long res = 1;
		while (b > 0) {
			if ((b & 1) == 1)
				res = res * a % m;
			a = a * a % m;
			b >>= 1;
		}
		return res;
	}
	static class tup implements Comparable<tup>{
		int a, b;
		tup(int a,int b){
			this.a=a;
			this.b=b;
		}
		@Override
		public int compareTo(tup o){
			return Integer.compare(o.b,b);
		}
	}
	static void shuffle(int[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(a.length);
			int temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}

	static void shuffle(long[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(a.length);
			long temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		public FastReader(String s) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(new File(s)));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.*;
/**
 *
 * @author arvin
 */
public class Main {

    static char a[][];
    static long dp[][];
    static int m,n;

    static long rec(int x,int y)
    {
        if(x==n-1 && y==m-1)
            return 1l;
        if(x>=n || y>=m || a[x][y]=='#')
            return 0l;
        long ab,ch;
        if(dp[x+1][y]==0)
            ch=rec(x+1,y);
        else
            ch=dp[x+1][y];
        if(dp[x][y+1]==0)
            ab=rec(x,y+1);
        else
            ab=dp[x][y+1];
        dp[x][y]=(ch+ab)%1000000007l;
        return dp[x][y];
    }

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        a=new char[n+1][m+1];
        dp=new long[n+1][m+1];
        sc.nextLine();
        for(int i=0;i<n;i++)
        {
            String abc=sc.nextLine();
            for(int j=0;j<m;j++)
                a[i][j]=abc.charAt(j);
        }

        System.out.println(rec(0,0));

         /*for(int i=0;i<n;i++)
         {
              for(int j=0;j<n;j++)
                System.out.print(dp[i][j]+" ");
              System.out.print("\n");
         }*/
        sc.close();
    }
}

Score : 100 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns.
Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.

For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}.
If a_{i, j} is ., Square (i, j) is an empty square; if a_{i, j} is #, Square (i, j) is a wall square.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square (1, 1) to (H, W).
As the answer can be extremely large, find the count modulo 10^9 + 7.

Constraints

H and W are integers.

2 \leq H, W \leq 1000

a_{i, j} is . or #.

Squares (1, 1) and (H, W) are empty squares.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W}

Output

Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5
..#..
.....
#...#
.....
..#..

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

Be sure to print the count modulo 10^9 + 7.


/*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;

public class Main {
/*********************************************Constants******************************************/
    static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static long mod=(long)1e9+7;
    static long mod1=998244353;
    static boolean sieve[];
    static ArrayList<Integer> primes;
    static ArrayList<Long> factorial;
    static HashSet<Integer> graph[];
/****************************************Solutions Begins*****************************************/
    static int n,m,input[][];
    static long dp[][];
    static boolean safe(int i,int j){
        if(i>=0&&j>=0&&i<n&&j<m&&input[i][j]!=0){
            return true;
        }
        return false;
    }
    static int dx[]={1,0};
    static int dy[]={0,1};
    static long dfs(int i,int j){
        if(i==n-1&&j==m-1){
            dp[i][j]=1;
            return 1;
        }
        if(dp[i][j]!=-1){
            return dp[i][j];
        }
        long ans=0;
        for(int k=0;k<2;k++){
            int x=i+dx[k];
            int y=j+dy[k];
            if(safe(x,y)){
                ans=(ans+dfs(x,y))%mod;
            }
        }
        dp[i][j]=ans;
        return ans;
    }
    public static void main (String[] args) throws Exception {
        String st[]=br.readLine().split(" ");
        n=Integer.parseInt(st[0]);
        m=Integer.parseInt(st[1]);
        input=new int[n][m];
        for(int i=0;i<n;i++){
            st=br.readLine().split(" ");
            for(int j=0;j<m;j++){
                if(st[0].charAt(j)=='.'){
                    input[i][j]=1;
                }
                else{
                    input[i][j]=0;
                }
            }
        }
        dp=new long[n][m];
        for(long arr[]:dp){
            Arrays.fill(arr,-1);
        }

        long ans=dfs(0,0);
        out.println(ans);
/****************************************Solutions Ends**************************************************/
        out.flush();
        out.close();
    }
/****************************************Template Begins************************************************/
/***************************************Precision Printing**********************************************/
    static void printPrecision(double d){
        DecimalFormat ft = new DecimalFormat("0.00000000000000000");
        out.println(ft.format(d));
    }
/******************************************Graph*********************************************************/
    static void Makegraph(int n){
        graph=new HashSet[n];
        for(int i=0;i<n;i++){
            graph[i]=new HashSet<>();
        }
    }
    static void addEdge(int a,int b){
        graph[a].add(b);
    }

/*********************************************PAIR********************************************************/
    static class PairComp implements Comparator<Pair>{
        public int compare(Pair p1,Pair p2){
            if(p1.u>p2.u){
                return 1;
            }
            else if(p1.u<p2.u){
                return -1;
            }
            else{
                return p1.v-p2.v;
            }
        }
    }
    static class Pair implements Comparable<Pair> {
        int u;
        int v;
        int index=-1;
        public Pair(int u, int v) {
            this.u = u;
            this.v = v;
        }

        public int hashCode() {
            int hu = (int) (u ^ (u >>> 32));
            int hv = (int) (v ^ (v >>> 32));
            return 31 * hu + hv;
        }

        public boolean equals(Object o) {
            Pair other = (Pair) o;
            return u == other.u && v == other.v;
        }

        public int compareTo(Pair other) {
            if(index!=other.index)
                return Long.compare(index, other.index);
            return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
        }

        public String toString() {
            return "[u=" + u + ", v=" + v + "]";
        }
    }

    static class PairCompL implements Comparator<Pairl>{
        public int compare(Pairl p1,Pairl p2){
            if(p1.u>p2.u){
                return 1;
            }
            else if(p1.u<p2.u){
                return -1;
            }
            else{
                return 0;
            }
        }
    }
    static class Pairl implements Comparable<Pair> {
            long u;
            long v;
            int index=-1;
            public Pairl(long u, long v) {
                this.u = u;
                this.v = v;
            }

            public int hashCode() {
                int hu = (int) (u ^ (u >>> 32));
                int hv = (int) (v ^ (v >>> 32));
                return 31 * hu + hv;
            }

            public boolean equals(Object o) {
                Pair other = (Pair) o;
                return u == other.u && v == other.v;
            }

            public int compareTo(Pair other) {
                if(index!=other.index)
                    return Long.compare(index, other.index);
                return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
            }

            public String toString() {
                return "[u=" + u + ", v=" + v + "]";
            }
        }
/*****************************************DEBUG***********************************************************/
    public static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
/************************************MODULAR EXPONENTIATION***********************************************/
    static long modulo(long a,long b,long c) {
        long x=1;
        long y=a;
        while(b > 0){
            if(b%2 == 1){
                x=(x*y)%c;
            }
            y = (y*y)%c; // squaring the base
            b /= 2;
        }
        return  x%c;
    }
/********************************************GCD**********************************************************/
    static long gcd(long x, long y)
    {
        if(x==0)
            return y;
        if(y==0)
            return x;
        long r=0, a, b;
        a = (x > y) ? x : y; // a is greater number
        b = (x < y) ? x : y; // b is smaller number
        r = b;
        while(a % b != 0)
        {
            r = a % b;
            a = b;
            b = r;
        }
        return r;
    }
/******************************************SIEVE**********************************************************/
    static void sieveMake(int n){
        sieve=new boolean[n];
        Arrays.fill(sieve,true);
        sieve[0]=false;
        sieve[1]=false;
        for(int i=2;i*i<n;i++){
            if(sieve[i]){
                for(int j=i*i;j<n;j+=i){
                    sieve[j]=false;
                }
            }
        }
        primes=new ArrayList<Integer>();
        for(int i=0;i<n;i++){
            if(sieve[i]){
                primes.add(i);
            }
        }
    }
/********************************************End***********************************************************/
}


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

class Main {
  static final Scanner in = new Scanner(System.in);
  static int N, K;

  static int[] a;
  static boolean dp[];

  public static void main(String[] args) throws Exception {
    N = in.nextInt();
    K = in.nextInt();
    a = new int[N];
    dp = new boolean[K + 1];

    for (int i = 0; i < N; i++) a[i] = in.nextInt();
    F();
    if (dp[K]) System.out.println("First"); else System.out.println("Second");
  }

  static boolean F(int k) {
    if (k < a[0]) return false;

    boolean win_state = false;
    for (int i = 0; i < N; i++) {
      if (k < a[i]) break;
      if (!F(k - a[i])) win_state = true;
    }

    return win_state;
  }

  static void F() {
    for (int k = 1; k <= a[0] && k <= K; k++) {
      dp[k] = false;
    }

    for (int k = a[0]; k <= K; k++) {
      boolean win_state = false;
      for (int i = 0; i < N; i++) {
        if(k < a[i])
          break;
        if (!dp[k - a[i]]) win_state = true;
      }
      dp[k] = win_state;
    }
  }
}

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second