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

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

    static class TaskC {
        static int n;
        static boolean[][] f;
        static int[][] p;

        static long dfs(boolean[] b, int cn, long max, boolean tf) {
            b[cn] = tf;
            long cMax = max;
            if (cn + 1 < b.length) {
                cMax = dfs(b, cn + 1, cMax, true);
            }
            if (cn + 1 < b.length) {
                cMax = dfs(b, cn + 1, cMax, false);
            }

            boolean opened = false;
            for (int i = 0; i < b.length; i++) {
                if (b[i]) {
                    opened = true;
                    break;
                }
            }
            if (!opened) return max;

            if (cn == b.length - 1) {
                int cProfit = 0;
                for (int i = 0; i < n; i++) {
                    int iCount = 0;
                    for (int j = 0; j < 10; j++) {
                        if (b[j] && f[i][j]) iCount++;
                    }
                    cProfit += p[i][iCount];
                }
                if (cProfit > cMax) cMax = cProfit;
            }
            return cMax;
        }

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            n = in.nextInt();
            f = new boolean[n][10];
            p = new int[n][11];

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 10; j++) {
                    int c = in.nextInt();
                    f[i][j] = (c == 1);
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 11; j++) {
                    int c = in.nextInt();
                    p[i][j] = c;
                }
            }

            boolean[] open = new boolean[10];
            long max = Long.MIN_VALUE;
            max = dfs(open, 0, max, false);
            max = dfs(open, 0, max, true);

            out.println(max);
        }

    }
}

Score : 300 points

Problem Statement

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already N stores in the street, numbered 1 through N.

You are given information of the business hours of those shops, F_{i,j,k}. If F_{i,j,k}=1, Shop i is open during Period k on Day j (this notation is explained below); if F_{i,j,k}=0, Shop i is closed during that period. Here, the days of the week are denoted as follows. Monday: Day 1, Tuesday: Day 2, Wednesday: Day 3, Thursday: Day 4, Friday: Day 5. Also, the morning is denoted as Period 1, and the afternoon is denoted as Period 2.

Let c_i be the number of periods during which both Shop i and Joisino's shop are open. Then, the profit of Joisino's shop will be P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

1≤N≤100

0≤F_{i,j,k}≤1

For every integer i such that 1≤i≤N, there exists at least one pair (j,k) such that F_{i,j,k}=1.

-10^7≤P_{i,j}≤10^7

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
F_{1,1,1} F_{1,1,2} ... F_{1,5,1} F_{1,5,2}
:
F_{N,1,1} F_{N,1,2} ... F_{N,5,1} F_{N,5,2}
P_{1,0} ... P_{1,10}
:
P_{N,0} ... P_{N,10}

Output

Print the maximum possible profit of Joisino's shop.

Sample Input 1

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

Sample Output 1

8

If her shop is open only during the periods when Shop 1 is opened, the profit will be 8, which is the maximum possible profit.

Sample Input 2

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

Sample Output 2

-2

Note that a shop must be open during at least one period, and the profit may be negative.

Sample Input 3

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

Sample Output 3

23


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.PriorityQueue;
import java.util.Queue;
import java.util.Set;
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();
        solver.solve(1, in, out);

        out.close();
    }

    // ======================================================================

    static class PPP {
    	public int key, val;
    	public PPP(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 Solver {
		public void solve(int testNumber, MyInput in, PrintWriter out) {
			String[] D =
				{"AKIHABARA","AKIHBR","AKIHABR","AKIHABAR","AKIHABRA","AKIHBAR","AKIHBARA","AKIHBRA",
					"KIHABARA","KIHBR","KIHABR","KIHABAR","KIHABRA","KIHBAR","KIHBARA","KIHBRA" };

			String S = in.nextString();
			boolean ans = false;
    		for(int i=1; i < D.length; i++) {
    			if(S.equals(D[i])) {
    				ans = true;
    				break;
    			}
    		}
    		if(ans)		out.println("YES");
    		else		out.println("NO");
        }
    }

    // ======================================================================
    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 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 {
        }
    }
}

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

Score : 300 points

Problem Statement

You are given a string S.

Takahashi can insert the character A at any position in this string any number of times.

Can he change S into AKIHABARA?

Constraints

1 \leq |S| \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If it is possible to change S into AKIHABARA, print YES; otherwise, print NO.

Sample Input 1

KIHBR

Sample Output 1

YES

Insert one A at each of the four positions: the beginning, immediately after H, immediately after B and the end.

Sample Input 2

AKIBAHARA

Sample Output 2

NO

The correct spell is AKIHABARA.

Sample Input 3

AAKIAHBAARA

Sample Output 3

NO

Submitted source-code file size, in bytes.

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

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


import java.util.*;

public class Main {

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

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        long[] L = new long[N + 1];

        L[0] = 2;
        L[1] = 1;

        for(int i = 2; i <= N; i++){
            L[i] = L[i - 1] + L[i - 2];
        }
        System.out.println(L[N]);
    }
}

Score : 200 points

Problem Statement

It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.

You are given an integer N. Find the N-th Lucas number.

Here, the i-th Lucas number L_i is defined as follows:

L_0=2

L_1=1

L_i=L_{i-1}+L_{i-2} (i≥2)

Constraints

1≤N≤86

It is guaranteed that the answer is less than 10^{18}.

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


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

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

	/**
	 * ASCII
	 * 0 48
	 * A 65
	 * a 97
	 */

	static PrintWriter pw = new PrintWriter(System.out);

	long MOD = 1_000_000_007;

	void solve() {
		FastScanner sc = new FastScanner();
		String s = sc.next();
		for (int i = 0; i < 1 << 3; i++) {
			int sum = s.charAt(0) - '0';
			StringBuilder sb = new StringBuilder(s);
			for (int j = 0; j < 3; j++) {
				if ((i >> j & 1) == 1) {
					sum += s.charAt(j+1) - '0';
					sb.insert(j*2+1, "+");
				} else {
					sum -= s.charAt(j+1) - '0';
					sb.insert(j*2+1, "-");
				}
			}
			if (sum == 7) {
				sb.append("=7");
				rout(sb.toString());
			}
		}
	}

	class Data {
		int a;
		int b;
		Data(int a, int b) {
			this.a = a;
			this.b = b;
		}
	}

	class UnionFind {
		int[] parents;
		int[] counts;

		public UnionFind(int size) {
			parents = new int[size];
			counts = new int[size];
			for (int i = 0; i < size; i++) {
				parents[i] = i;
				counts[i] = 1;
			}
		}

		public int find(int a) {
			if (parents[a] == a) return a;
			parents[a] = find(parents[a]);
			return parents[a];
		}

		public void unite(int a, int b) {
			a = find(a);
			b = find(b);
			if (a == b) return;
			if (counts[a] < counts[b]) {
				parents[a] = b;
				counts[b] += counts[a];
			} else {
				parents[b] = a;
				counts[a] += counts[b];
			}
		}

		public boolean differ(int a, int b) {
			a = find(a);
			b = find(b);
			return a != b;
		}

		public int count(int a) {
			return counts[find(a)];
		}
	}

	class Combination {
		final int mod;
		final int max;

		final long[] fact;
		final long[] inv;
		final long[] invfact;

		public Combination(int n) {
			this(n, 1_000_000_007);
		}

		public Combination(int n, int mod) {
			this.mod = mod;
			max = n + 1;
			fact = new long[max];
			invfact = new long[max];
			inv = new long[max];

			inv[1] = 1;
			for (int i = 2; i < inv.length; i++) {
				inv[i] = inv[mod % i] * (mod - mod / i) % mod;
			}

			fact[0] = 1;
			invfact[0] = 1;
			for (int i = 1; i < inv.length; i++) {
				fact[i] = i * fact[i - 1] % mod;
				invfact[i] = inv[i] * invfact[i - 1] % mod;
			}
		}

		public long get(int n, int r) {
			return fact[n] * invfact[n - r] % mod * invfact[r] % mod;
		}
	}

	public long gcd(long a, long b) {
		if (b == 0) return a;
		else return gcd(b, a%b);
	}

	public void reverse(int[] a) {
		int last = a.length-1;
		int n = a.length / 2;
		for (int i = 0; i < n; i++) {
			int t = a[i];
			a[i] = a[last-i];
			a[last-i] = t;
		}
	}

	public void reverse(long[] a) {
		int last = a.length-1;
		int n = a.length / 2;
		for (int i = 0; i < n; i++) {
			long t = a[i];
			a[i] = a[last-i];
			a[last-i] = t;
		}
	}

	void out(String a) {
		pw.println(a);
	}
	void out(boolean a) {
		pw.println(a);
	}

	void out(int a) {
		pw.println(a);
	}

	void out(long a) {
		pw.println(a);
	}

	void out(double a) {
		pw.println(a);
	}

	void out(char a) {
		pw.println(a);
	}

	void rout(String a) {
		out(a);
		pw.close();
		System.exit(0);
	}
	void rout(int a) {
		out(a);
		pw.close();
		System.exit(0);
	}
	void rout(long a) {
		out(a);
		pw.close();
		System.exit(0);
	}
	void rout(double a) {
		out(a);
		pw.close();
		System.exit(0);
	}
	void rout(char a) {
		out(a);
		pw.close();
		System.exit(0);
	}
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


import java.util.*;

public class Main {

	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		char x = sc.next().charAt(0);
		char y = sc.next().charAt(0);
		if (x < y) {
			System.out.println("<");
		} else if (x == y) {
			System.out.println("=");
		} else {
			System.out.println(">");
		}
	}
}

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


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

/**
 * for (int i = 0; i < N; i++) {}
 * System.out.println();
 * HashMap<Integer, Integer> hm = new HashMap<>();
 * int[] s = new int[M];
 * ArrayDeque<Integer> deq = new ArrayDeque<>();
 *
 */
public class Main implements Runnable { //クラス名はSnukeFestival

	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.exit(1));
		new Thread(null, new Main(), "", 16 * 1024 * 1024).start(); //16MBスタックを確保して実行
	}

	public void run() {
		FastScannerSnukeFestival sc = new FastScannerSnukeFestival(System.in);

		try {
			//String S = sc.nextLine().trim();
			int N = sc.nextInt();
			double[] a = new double[N];
			double[] b = new double[N];
			double[] c = new double[N];
			//long l = sc.nextLong();
			//ArrayList<Integer> arr = new ArrayList<Integer>();

			for (int i = 0; i < N; i++) {
				a[i] = sc.nextLong();
			}

			for (int i = 0; i < N; i++) {
				b[i] = sc.nextLong();
			}

			for (int i = 0; i < N; i++) {
				c[i] = sc.nextLong();
			}

			Arrays.sort(a);
			Arrays.sort(c);

			long ans = 0;
			long numa = 0;
			long numc = 0;
			for (int i = 0; i < N; i++) {
				/**
				 * binarySearchメソッドの戻り値は、
				 * listの中に該当する値があるときはその値の格納場所を返す。indexは0から始まる。
				 *
				 * 該当する値がないときは、その値が格納されるであろう場所の符号をマイナスにし、その値にさらに1を引いた値が返される。
				 * 符号をマイナスにするだけであると先頭に格納されたとき(index=0)は該当する値があるときとないときでは区別できなくなってしまうため、1を引く必要がある。
				 */
				//System.out.println(b[i]);
				//System.out.println(Arrays.binarySearch(a, b[i] - 0.1));
				numa = Arrays.binarySearch(a, b[i] - 0.1);
				//System.out.println(Arrays.binarySearch(c, b[i] + 0.1));
				numc = Arrays.binarySearch(c, b[i] + 0.1);

				numa = 0 - (numa + 1);
				numc = 0 - (numc + 1);

				//System.out.println(numa + " " + numc);

				if (numa > 0 && numc < N) {
					ans += numa * (N - numc);
				}
				//System.out.println("ans " + ans);
			}

			System.out.println(ans);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

//高速なScanner
class FastScannerSnukeFestival {
	private BufferedReader reader = null;
	private StringTokenizer tokenizer = null;

	public FastScannerSnukeFestival(InputStream in) {
		reader = new BufferedReader(new InputStreamReader(in));
		tokenizer = null;
	}

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

	public String nextLine() {
		if (tokenizer == null || !tokenizer.hasMoreTokens()) {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken("\n");
	}

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

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

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

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

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

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


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

public class Main {

    FastScanner in;
    PrintWriter out;

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

    void solve() {
        int N = in.nextInt();
        int[] A = new int[N];
        int[] B = new int[N];
        int[] C = new int[N];
        for (int i = 0; i < N; i++) {
            A[i] = in.nextInt();
        }
        for (int i = 0; i < N; i++) {
            B[i] = in.nextInt();
        }
        for (int i = 0; i < N; i++) {
            C[i] = in.nextInt();
        }
        Arrays.sort(A);
        Arrays.sort(B);
        Arrays.sort(C);
        long result = 0;
        int startb = 0;
        int startc = 0;
        for (int i = 0; i < N; i++) {
            // round of array A
            for (int j = startb; j < N; j++) {
                //round of array B
                if (A[i] >= B[j]) {
                    startb = j;
                    continue;
                }
                for (int k = startc; k < N; k++) {
                    //round of array C
                    if (B[j] >= C[k]) {
                        if (startb >= C[k]) {
                            startc = k;
                        }
                        continue;
                    } else {
                        result += C.length - k;
                        break;
                    }
                }
            }
        }
        out.println(result);
    }

    void run() {
        in = new FastScanner();
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    public class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

        public FastScanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

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

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

}


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

public class Main {

    FastScanner in;
    PrintWriter out;

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

    void solve() {
        int N = in.nextInt();
        int[] A = new int[N];
        int[] B = new int[N];
        int[] C = new int[N];
        for (int i = 0; i < N; i++) {
            A[i] = in.nextInt();
        }
        for (int i = 0; i < N; i++) {
            B[i] = in.nextInt();
        }
        for (int i = 0; i < N; i++) {
            C[i] = in.nextInt();
        }
        long result = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (A[i] >= B[j]) {
                    continue;
                }
                for (int k = 0; k < N; k++) {
                    if (B[j] >= C[k]) {
                        continue;
                    } else {
                        result += 1L;
                    }
                }
            }
        }
        out.println(result);
    }

    void run() {
        in = new FastScanner();
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    public class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

        public FastScanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

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

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

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author daltao
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "daltao", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            TaskD solver = new TaskD();
            solver.solve(1, in, out);
            out.close();
        }
    }
    static class TaskD {
        int inf = (int) 1e8;

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int k = in.readInt();
            if (k == 100000) {
                out.println(1);
                return;
            }

            int round = 200;
            int limit = 100000;
            int[][] dp = new int[round + 1][limit];
            SequenceUtils.deepFill(dp, inf);
            dp[0][k] = 0;
            for (int i = 1; i <= round; i++) {
                for (int j = 0; j < 10; j++) {
                    int val = k * j;
                    for (int t = 0; t < limit; t++) {
                        int transform = (val + t) / 10;
                        dp[i][transform] = Math.min(dp[i][transform], dp[i - 1][t] + (val + t) % 10);
                    }
                }
            }

            int ans = inf;
            DigitUtils.DigitBase base = new DigitUtils.DigitBase(10);
            for (int i = 0; i < limit; i++) {
                int sum = 0;
                for (int j = 0; j < 6; j++) {
                    sum += base.getBit(i, j);
                }
                ans = Math.min(ans, sum + dp[round][i]);
            }

            out.println(ans);
        }

    }
    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(int c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
    static class SequenceUtils {
        public static void deepFill(Object array, int val) {
            if (!array.getClass().isArray()) {
                throw new IllegalArgumentException();
            }
            if (array instanceof int[]) {
                int[] intArray = (int[]) array;
                Arrays.fill(intArray, val);
            } else {
                Object[] objArray = (Object[]) array;
                for (Object obj : objArray) {
                    deepFill(obj, val);
                }
            }
        }

    }
    static class LongList {
        private int size;
        private int cap;
        private long[] data;
        private static final long[] EMPTY = new long[0];

        public LongList(int cap) {
            this.cap = cap;
            if (cap == 0) {
                data = EMPTY;
            } else {
                data = new long[cap];
            }
        }

        public LongList(LongList list) {
            this.size = list.size;
            this.cap = list.cap;
            this.data = Arrays.copyOf(list.data, size);
        }

        public LongList() {
            this(0);
        }

        private void ensureSpace(int need) {
            int req = size + need;
            if (req > cap) {
                while (cap < req) {
                    cap = Math.max(cap + 10, 2 * cap);
                }
                data = Arrays.copyOf(data, cap);
            }
        }

        private void checkRange(int i) {
            if (i < 0 || i >= size) {
                throw new ArrayIndexOutOfBoundsException();
            }
        }

        public long tail() {
            checkRange(0);
            return data[size - 1];
        }

        public void add(long x) {
            ensureSpace(1);
            data[size++] = x;
        }

        public long[] toArray() {
            return Arrays.copyOf(data, size);
        }

        public String toString() {
            return Arrays.toString(Arrays.copyOf(data, size));
        }

    }
    static class DigitUtils {
        private static final long[] DIGIT_VALUES = new long[19];
        static {
            DIGIT_VALUES[0] = 1;
            for (int i = 1; i < 19; i++) {
                DIGIT_VALUES[i] = DIGIT_VALUES[i - 1] * 10;
            }
        }

        private DigitUtils() {}

        public static boolean isMultiplicationOverflow(long a, long b, long limit) {
            if (limit < 0) {
                limit = -limit;
            }
            if (a < 0) {
                a = -a;
            }
            if (b < 0) {
                b = -b;
            }
            if (a == 0 || b == 0) {
                return false;
            }
            return a > limit / b;
        }

        public static class DigitBase {
            private long[] pow;
            private long base;

            public DigitBase(long base) {
                if (base <= 1) {
                    throw new IllegalArgumentException();
                }
                this.base = base;
                LongList ll = new LongList(64);
                ll.add(1);
                while (!isMultiplicationOverflow(ll.tail(), base, Long.MAX_VALUE)) {
                    ll.add(ll.tail() * base);
                }
                pow = ll.toArray();
            }

            public int getBit(long x, int i) {
                return (int) (x / pow[i] % base);
            }

        }

    }
    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }
}

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


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

public class Main {

	private static Scanner sc;
	private static Printer pr;

	private static void solve() {
		int k = sc.nextInt();

		List<List<Integer>> edges0 = new ArrayList<>(k);
		List<List<Integer>> edges1 = new ArrayList<>(k);
		for (int i = 0; i < k; i++) {
			edges0.add(new ArrayList<>());
			edges1.add(new ArrayList<>());
		}

		for (int i = 0; i < k; i++) {
			edges1.get(i).add((i + 1) % k);
			edges0.get(i).add((i * 10) % k);
		}

		int[] d = new int[k];
		Arrays.fill(d, Integer.MAX_VALUE / 2);
		Deque<Integer> q = new ArrayDeque<>();
		q.add(1);
		d[1] = 1;
		while (!q.isEmpty()) {
			int e = q.remove();

			if (e == 0) {
				pr.println(d[0]);
				return;
			}

			for (int next : edges0.get(e)) {
				if (d[next] > d[e]) {
					q.addFirst(next);
					d[next] = d[e];
				}
			}
			for (int next : edges1.get(e)) {
				if (d[next] > d[e] + 1) {
					q.addLast(next);
					d[next] = d[e] + 1;
				}
			}
		}
	}

	// ---------------------------------------------------
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		pr = new Printer(System.out);

		solve();

		pr.close();
		sc.close();
	}

	@SuppressWarnings("unused")
	private static class Scanner {
		BufferedReader br;

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

		private boolean isPrintable(int ch) {
			return ch >= '!' && ch <= '~';
		}

		private boolean isCRLF(int ch) {
			return ch == '\n' || ch == '\r' || ch == -1;
		}

		private int nextPrintable() {
			try {
				int ch;
				while (!isPrintable(ch = br.read())) {
					if (ch == -1) {
						throw new NoSuchElementException();
					}
				}

				return ch;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		String next() {
			try {
				int ch = nextPrintable();
				StringBuilder sb = new StringBuilder();
				do {
					sb.appendCodePoint(ch);
				} while (isPrintable(ch = br.read()));

				return sb.toString();
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		int nextInt() {
			try {
				// parseInt from Integer.parseInt()
				boolean negative = false;
				int res = 0;
				int limit = -Integer.MAX_VALUE;
				int radix = 10;

				int fc = nextPrintable();
				if (fc < '0') {
					if (fc == '-') {
						negative = true;
						limit = Integer.MIN_VALUE;
					} else if (fc != '+') {
						throw new NumberFormatException();
					}
					fc = br.read();
				}
				int multmin = limit / radix;

				int ch = fc;
				do {
					int digit = ch - '0';
					if (digit < 0 || digit >= radix) {
						throw new NumberFormatException();
					}
					if (res < multmin) {
						throw new NumberFormatException();
					}
					res *= radix;
					if (res < limit + digit) {
						throw new NumberFormatException();
					}
					res -= digit;

				} while (isPrintable(ch = br.read()));

				return negative ? res : -res;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		long nextLong() {
			try {
				// parseLong from Long.parseLong()
				boolean negative = false;
				long res = 0;
				long limit = -Long.MAX_VALUE;
				int radix = 10;

				int fc = nextPrintable();
				if (fc < '0') {
					if (fc == '-') {
						negative = true;
						limit = Long.MIN_VALUE;
					} else if (fc != '+') {
						throw new NumberFormatException();
					}
					fc = br.read();
				}
				long multmin = limit / radix;

				int ch = fc;
				do {
					int digit = ch - '0';
					if (digit < 0 || digit >= radix) {
						throw new NumberFormatException();
					}
					if (res < multmin) {
						throw new NumberFormatException();
					}
					res *= radix;
					if (res < limit + digit) {
						throw new NumberFormatException();
					}
					res -= digit;

				} while (isPrintable(ch = br.read()));

				return negative ? res : -res;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		float nextFloat() {
			return Float.parseFloat(next());
		}

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

		String nextLine() {
			try {
				int ch;
				while (isCRLF(ch = br.read())) {
					if (ch == -1) {
						throw new NoSuchElementException();
					}
				}
				StringBuilder sb = new StringBuilder();
				do {
					sb.appendCodePoint(ch);
				} while (!isCRLF(ch = br.read()));

				return sb.toString();
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		void close() {
			try {
				br.close();
			} catch (IOException e) {
//				throw new NoSuchElementException();
			}
		}
	}

	private static class Printer extends PrintWriter {
		Printer(PrintStream out) {
			super(out);
		}
	}
}


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

public class Main {
	public static void main(String[] args) throws IOException {
		Main mainObj = new Main();
		mainObj.solve();
	}

	public void solve() throws IOException {
		FastScanner fs = new FastScanner();
		int n = fs.nextInt();
		int k = fs.nextInt();

		int ans = 1;

		for(int i = 0; i < n; i++) {
			if(ans > k) {
				ans *= 2;
			}else {
				ans += k;
			}
		}

		System.out.println(ans);
	}

	public class FastScanner {

		BufferedReader reader;
		private StringTokenizer st;

		public FastScanner() {
			st = null;
			reader = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() throws IOException {
			if (st == null || !st.hasMoreElements()) {
				st = new StringTokenizer(reader.readLine());
			}
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			st = null;
			String readLine = null;
			readLine = reader.readLine();
			return readLine;
		}

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

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

		public int[] nextIntArr(int n) throws NumberFormatException, IOException {
			int[] retArr = new int[n];
			for (int i = 0; i < n; i++) {
				retArr[i] = nextInt();
			}
			return retArr;
		}

		public long[] nextLongArr(int n) throws NumberFormatException, IOException {
			long[] retArr = new long[n];
			for (int i = 0; i < n; i++) {
				retArr[i] = nextLong();
			}
			return retArr;
		}

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

}

Score : 200 points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer 1.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total.
Find the minimum possible value displayed in the board after N operations.

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 7 → 10.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 8 → 16 → 26 → 36 → 46 → 56 → 66 → 76.

By the way, this contest is AtCoder Beginner Contest 076.


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

class Main {
	public static void main(String args[]) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		Solver solver = new Solver();
		solver.init();
		solver.readHead(in.readLine());
		for (; solver.hasNext();) {
			solver.readBody(in.readLine());
		}
		solver.solve();
	}
}

class Solver {
	int N;
	int cnt;
	int K;

	public void init() {
		N = 0;
		cnt = 0;
		K = 0;
	}

	public void readHead(String str) {
		String[] strArr = str.split(" ");
		N = Integer.parseInt(strArr[0]);
		// System.out.println(N);
	}

	public boolean hasNext() {
		// return cnt < N;
		return cnt < 1;
	}

	public void readBody(String str) {
		// System.out.println(str);
		cnt++;
		K = Integer.parseInt(str);
	}

	public void solve() {
		int ans = 1;
		for (; N > 0 && ans < K; N--) {
			ans *= 2;
		}
		ans += N * K;
		System.out.println(ans);
	}
}


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

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

    static void solve(Scanner scanner) {
        int N = Integer.parseInt(scanner.nextLine());
        int[] ts = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        for (int i = 1; i < N; i++) {
            ts[i] += ts[i - 1];
        }
        int[] vs = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        BigDecimal[] dp = new BigDecimal[200 * 100 + 1];
        Arrays.fill(dp, BigDecimal.ZERO);
        int curr = 0;
        for (int i = 1; i < 200 * 100 + 1; i++) {
            if (i >= 2 * ts[N - 1] && dp[i - 1].compareTo(BigDecimal.ZERO) == 0) {
                break;
            }
            BigDecimal vNext = curr == N - 1 ? BigDecimal.ZERO : BigDecimal.valueOf(vs[curr + 1]);
            if (dp[i - 1].subtract(vNext).compareTo(BigDecimal.valueOf(ts[curr]).subtract(BigDecimal.valueOf(i - 1).divide(BigDecimal.valueOf(2)))) == 0) {
                dp[i] =  dp[i - 1].subtract(BigDecimal.valueOf(0.5));
            } else if (BigDecimal.valueOf(vs[curr]).compareTo(dp[i - 1]) > 0) {
                dp[i] =  dp[i - 1].add(BigDecimal.valueOf(0.5));
            } else if (BigDecimal.valueOf(vs[curr]).compareTo(dp[i - 1]) == 0) {
                dp[i] =  dp[i - 1];
            }
            // System.out.printf("%.1f %.1f \n", i / 2.0, dp[i].doubleValue());
            if (curr != N - 1 && 2 * ts[curr] == i) {
                curr++;
            }
        }
        System.out.printf("%.6f\n", Arrays.stream(dp).mapToDouble(BigDecimal::doubleValue).sum() / 2.0);
    }

}

Score : 400 points

Problem Statement

In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.

In the plan developed by the president Takahashi, the trains will run as follows:

A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.

In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.

According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.

Find the maximum possible distance that a train can cover in the run.

Constraints

1 \leq N \leq 100

1 \leq t_i \leq 200

1 \leq v_i \leq 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N

Output

Print the maximum possible that a train can cover in the run.

Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.

Sample Input 1

1
100
30

Sample Output 1

2100.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 30 seconds, it accelerates at a rate of 1m/s^2, covering 450 meters.

In the subsequent 40 seconds, it maintains the velocity of 30m/s, covering 1200 meters.

In the last 30 seconds, it decelerates at the acceleration of -1m/s^2, covering 450 meters.

The total distance covered is 450 + 1200 + 450 = 2100 meters.

Sample Input 2

2
60 50
34 38

Sample Output 2

2632.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 34 seconds, it accelerates at a rate of 1m/s^2, covering 578 meters.

In the subsequent 26 seconds, it maintains the velocity of 34m/s, covering 884 meters.

In the subsequent 4 seconds, it accelerates at a rate of 1m/s^2, covering 144 meters.

In the subsequent 8 seconds, it maintains the velocity of 38m/s, covering 304 meters.

In the last 38 seconds, it decelerates at the acceleration of -1m/s^2, covering 722 meters.

The total distance covered is 578 + 884 + 144 + 304 + 722 = 2632 meters.

Sample Input 3

3
12 14 2
6 2 7

Sample Output 3

76.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 6 seconds, it accelerates at a rate of 1m/s^2, covering 18 meters.

In the subsequent 2 seconds, it maintains the velocity of 6m/s, covering 12 meters.

In the subsequent 4 seconds, it decelerates at the acceleration of -1m/s^2, covering 16 meters.

In the subsequent 14 seconds, it maintains the velocity of 2m/s, covering 28 meters.

In the last 2 seconds, it decelerates at the acceleration of -1m/s^2, covering 2 meters.

The total distance covered is 18 + 12 + 16 + 28 + 2 = 76 meters.

Sample Input 4

1
9
10

Sample Output 4

20.250000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 4.5 seconds, it accelerates at a rate of 1m/s^2, covering 10.125 meters.

In the last 4.5 seconds, it decelerates at the acceleration of -1m/s^2, covering 10.125 meters.

The total distance covered is 10.125 + 10.125 = 20.25 meters.

Sample Input 5

10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70

Sample Output 5

20291.000000000000


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int n = s.length();
		int ans = 0, l = 0, r = n - 1;
		if(n == 1) {
			System.out.println(0);
			return;
		}
		for(; ; ) {
			if(s.charAt(l) == s.charAt(r)) {
				l++; r--;
			} else {
				if(s.charAt(l) != 'x' && s.charAt(r) != 'x') {
					System.out.println(-1);
					return;
				} else {
					if(s.charAt(l) == 'x') {
						l++;
						ans++;
						if(l == r) {
							System.out.println(ans);
							return;
						}
					}
					if(s.charAt(r) == 'x') {
						r--;
						ans++;
						if(l == r) {
							System.out.println(ans);
							return;
						}
					}
				}
			}
		}
	}
}

Score : 400 points

Problem Statement

We have a string s consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in s of his choice, including the beginning and end of s.

Snuke's objective is to turn s into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and abcba are palindromes, while ab, abab and abcda are not.

Constraints

1 \leq |s| \leq 10^5

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn s into a palindrome.

Sample Input 3

a

Sample Output 3

0

s is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx


import java.util.Scanner;

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

        String s = scanner.next();

        int xCount = 0;
        String newStr = "";

        for (int i = 0; i < s.length(); i++) {
            String tmp = s.substring(i, i + 1);
            if (tmp.equals("x")) {
                if (!(s.length() % 2 == 1 && i == (s.length() - 1) / 2)) {
                    xCount++;
                }
            } else {
                newStr += tmp;
            }
        }

        if (newStr.length() == 0) {
            System.out.println(0);
        } else if (check(newStr)) {
            System.out.println(xCount);
        } else {
            System.out.println(-1);
        }
    }

    private static boolean check(String s) {
        int l = s.length();
        if (l % 2 == 1) {
            for (int i = 0; i < (l - 1) / 2; i++) {
                if (!s.substring(i, i + 1).equals(s.substring(l - 1 - i, l - i))) {
                    return false;
                }
            }
        } else {
            for (int i = 0; i < l / 2; i++) {
                if (!s.substring(i, i + 1).equals(s.substring(l - 1 - i, l - i))) {
                    return false;
                }
            }
        }
        return true;
    }
}


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

class Main {
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static PrintWriter pw = new PrintWriter(System.out);
    public static String line;
    public static StringTokenizer st;
    public static ArrayList<ArrayList<Integer>> adjList;
    public static int[] dx = {-1, 0, 1, 0, -1, 1, 1, -1};
    public static int[] dy = {0, 1, 0, -1, 1, 1, -1, -1};
    public static int INF = 0x3f3f3f3f;
    public static int MOD = 1000000007;

    public static void main(String[] args) throws Exception{
        String s = br.readLine();
        int xCount = 0;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == 'x'){
                xCount++;
            } else{
                sb.append(s.charAt(i));
            }
        }

        // System.out.println(sb.reverse().toString() + " " + sb.toString());
        if(sb.toString().equals(sb.reverse().toString())){
            int i = 0;
            int j = s.length() - 1;
            int ans = 0;
            while(i < j){
                char a = s.charAt(i);
                char b = s.charAt(j);

                if(a == b){
                    i++;
                    j--;
                } else if(a == 'x'){
                    i++;
                    ans++;
                } else{
                    j--;
                    ans++;
                }
            }
            pw.print(ans + "\n");
        } else{
            pw.print("-1\n");
        }

        pw.close();
        br.close();
    }
}

class Pair{
    public long x, y;

    Pair(long _x, long _y){
        x = _x;
        y = _y;
    }
}
class Point implements Comparable<Point>{
    public double x, y;

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

    public int compareTo(Point p){
        if(x != p.x) return x < p.x ? -1 : 1;
        else if(y != p.y) return y < p.y ? -1 : 1;
        return 0;
    }
}


import java.util.*;

public class Main {
	public static void main(String[] args) {
		D();
		return;
	}

	public static void A() {
		Scanner sc = new Scanner(System.in);
		int A = sc.nextInt();
		int B = sc.nextInt();
		int C = sc.nextInt();

		if(A==B) System.out.println(C);
		else if(B==C) System.out.println(A);
		else System.out.println(B);
	}

	// #を読めば、その周囲に数字を入れる
	// -1は#に対応する 空間O(n)
	//あるいは、ますの８方向を確認する　時間O(n)　空間O(1）

	public static void calc8(char[][] cell ,int h, int w) {
		if(cell[h][w] == '#') System.out.print('#');
		else {
			int[] hs = new int[] {h-1,h,h+1};
			int[] ws = new int[] {w-1,w,w+1};
			int sum = 0;
			for(int nh: hs) {
				for(int nw : ws) {
					if(nh<cell.length && nh>=0 && nw >=0 && nw < cell[0].length) {
						if(cell[nh][nw]=='#') sum++;
					}
				}
			}
			System.out.print(sum);
		}
		if(w == cell[0].length-1) System.out.println("");
	}

	public static void B() {
		Scanner sc = new Scanner(System.in);
		int H = sc.nextInt();
		int W = sc.nextInt();
		char[][] cell = new char[H][W];
		for(int i=0;i<H;i++) {
			String s = sc.next();
			for(int j=0; j<W;j++) {
				cell[i][j] = s.charAt(j);
			}
		}
		for(int i=0;i<H;i++) {
			for(int j=0;j<W;j++) {
				calc8(cell,i,j);
			}
		}
	}

	//グラフが大きいならば、双方向探索も有効
	//最初は連結と仮定した場合
	// 隣接行列matに置いて、iとjが連結か調べる　WFS
	public static boolean connect(int[][] mat, int i, int j) {
		boolean[] visit = new boolean[mat.length];
		LinkedList<Integer> que = new LinkedList<Integer>();
		que.add(i);
		while(!que.isEmpty()) {
			int check = que.removeFirst();
			if(check == j) return true;
			//System.out.println(check + " check");
			visit[check] = true;
			for(int w=0;w<mat.length;w++) {
				if (mat[check][w] == 1 && (!visit[w])) {
					//System.out.println(mat[check][w] + "e");
					que.add(w);
					visit[w] = true;
				}
			}
		}
		return false;
	}
	public static void C() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int[][] mat = new int[N][N];
		int[][] edge = new int[M][2];
		for(int i=0;i<M;i++) {
			int a = sc.nextInt()-1;
			int b = sc.nextInt()-1;
			mat[a][b] = mat[b][a] = 1;
			edge[i] = new int[] {a,b};
		}
		int count = 0;
		for(int i=0;i<M;i++) {
			int a = edge[i][0];
			int b = edge[i][1];
			mat[a][b] = mat[b][a] = 0;
			if(!connect(mat,a,b)) count++;
			mat[a][b] = mat[b][a] = 1;
		}
		System.out.println(count);
	}

	// N^4の長方形
	//点が含まれるかを確認
	public static int containdpoint(int[][] lis, int xl, int xr, int yd, int yu) {
		int count = 0;
		for(int i=0;i<lis.length;i++) {
			int x = lis[i][0];
			int y = lis[i][1];
			//System.out.println(x + " " + y + " " + xl + " " + xr);
			if(xl <= x && x<=xr && yd<=y && y<=yu) count++;
		}
		//System.out.println(count);
		return count;
	}

	public static void D() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int K = sc.nextInt();
		int[] xs = new int[N];
		int[] ys = new int[N];
		int[][] lis = new int[N][2];
		for(int i=0;i<N;i++) {
			xs[i] = lis[i][0] = sc.nextInt();
			ys[i] = lis[i][1] = sc.nextInt();
		}
		Arrays.sort(xs);
		Arrays.sort(ys);
		long min = Long.MAX_VALUE;
		for(int xlidx = 0; xlidx<N-1; xlidx++) {
			for(int xridx = xlidx+1;xridx<N;xridx++) {
				for(int ydidx = 0; ydidx<N-1; ydidx++) {
					for(int yuidx = ydidx+1; yuidx < N; yuidx++) {
						if (containdpoint(lis, xs[xlidx],xs[xridx],ys[ydidx],ys[yuidx])>=K) {
							min = Math.min(min, (xs[xridx]-xs[xlidx])*(long)(ys[yuidx]-ys[ydidx]));
						}
					}
				}
			}
		}
		System.out.println(min);
	}
}

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

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

    static class DAxisParallelRectangle {
        public void solve(int testNumber, LightScanner in, PrintWriter out) {
            int n = in.ints(), k = in.ints();
            IntPair[] rx = new IntPair[n];
            in.objs(rx, IntPair::new);
            Arrays.sort(rx, Comparator.comparing(r -> r.key));
            IntPair[] ry = rx.clone();
            Arrays.sort(ry, Comparator.comparing(r -> r.value));

            long ans = Long.MAX_VALUE;
            for (int xs = 0; xs <= n - k; xs++) {
                for (int ys = 0; ys <= n - k; ys++) {
                    for (int xe = xs; xe < n; xe++) {
                        for (int ye = ys; ye < n; ye++) {
                            int count = 0;
                            for (int i = xs; i < n; i++) {
                                if (rx[i].key <= rx[xe].key && ry[ys].value <= rx[i].value && rx[i].value <= ry[ye].value) {
                                    count++;
                                }
                            }
                            if (count >= k) {
                                ans = Math.min(ans, (rx[xe].key - rx[xs].key) * (long) (ry[ye].value - ry[ys].value));
                            }
                        }
                    }
                }
            }
            out.println(ans);
        }

    }

    static class IntPair {
        public int key;
        public int value;

        public IntPair(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            return Objects.equals(key, pair.key) &&
                    Objects.equals(value, pair.value);
        }

        public int hashCode() {
            return Objects.hash(key, value);
        }

        public String toString() {
            return "Pair{" +
                    "key=" + key +
                    ", value=" + value +
                    '}';
        }

    }

    static interface BiIntFunction<T> {
        T apply(int t, int u);

    }

    static class LightScanner {
        private BufferedReader reader = null;
        private StringTokenizer tokenizer = null;

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

        public String string() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ints() {
            return Integer.parseInt(string());
        }

        public <T> void objs(T[] array, BiIntFunction<T> constructor) {
            for (int i = 0; i < array.length; i++) {
                array[i] = constructor.apply(ints(), ints());
            }
        }

    }

    static final class Pair<K, V> {
        public K key;
        public V value;

        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            return Objects.equals(key, pair.key) &&
                    Objects.equals(value, pair.value);
        }

        public int hashCode() {
            return Objects.hash(key, value);
        }

        public String toString() {
            return "Pair{" +
                    "key=" + key +
                    ", value=" + value +
                    '}';
        }

    }
}


import java.util.Scanner;

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

		String s = sc.next();

		System.out.println(s.substring(0, s.length() - 8));
	}

}

Score : 100 points

Problem Statement

Rng is going to a festival.

The name of the festival is given to you as a string S, which ends with FESTIVAL, from input. Answer the question: "Rng is going to a festival of what?" Output the answer.

Here, assume that the name of "a festival of s" is a string obtained by appending FESTIVAL to the end of s.
For example, CODEFESTIVAL is a festival of CODE.

Constraints

9 \leq |S| \leq 50

S consists of uppercase English letters.

S ends with FESTIVAL.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer to the question: "Rng is going to a festival of what?"

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE

This is the same as the example in the statement.

Sample Input 2

CODEFESTIVALFESTIVAL

Sample Output 2

CODEFESTIVAL

This string is obtained by appending FESTIVAL to the end of CODEFESTIVAL, so it is a festival of CODEFESTIVAL.

Sample Input 3

YAKINIKUFESTIVAL

Sample Output 3

YAKINIKU


import java.util.Scanner;

public class Main {

	public static final int MAX = 3500;

	public static void main(String args[]) {

		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();

		for(int h=1;h<=MAX;h++) {
			for(int n=1;n<=MAX;n++) {
				int child = N*h*n;
				int mother = 4*h*n - N*n - N*h;

				if(mother != 0 && child%mother == 0 && child/mother > 0) {
					System.out.println(h + " " + n + " " + (child/mother));
					return;
				}

			}
		}
	}
}

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


import java.util.*;

// Tenakaichi
// https://yukicoder.me/problems/no/325

public class Main {

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

		double E = 1e-9;

		double N = in.nextDouble();
		boolean answerFound = false;
		double d = 4 / N;

		for (double i = 3500; i > 0 && 1 / i < d && !answerFound; i--) {
			double dd = d - 1 / i;

			for (double j = 3500; j > 0 && 1 / j < dd && !answerFound; j--) {
				double ddd = dd - 1 / j;

				double x = 1 / ddd;
				int k = 0;

				if (Math.abs(Math.ceil(x) - x) <= E) {
					k = (int) Math.ceil(x);
					answerFound = true;
				} else if (Math.abs(Math.floor(x) - x) <= E) {
					k = (int) Math.floor(x);
					answerFound = true;
				}

				if (answerFound) {
					System.out.printf("%d %d %d\n", (int) i, (int) j, k);
				}
			}
		}
	}

}


import static java.lang.System.out;
import java.io.InputStream;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Main {
	public static void main(String args[]) {
		MyInput in = new MyInput();
    int N = in.nextInt();
    int t = 0;
    int m = 0;
    int tmp = 0;
    for(int i = 0; i < N; i++) {
        tmp = in.nextInt();
        if(tmp > t) {
            t = tmp;
            m = in.nextInt();
        }
        else in.nextInt();
    }
    out.println(t + m);

	}
}

class MyInput {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr= 0;
	private int buflen = 0;
	private boolean hasNextByte() {
		if(ptr < buflen) {
			return true;
		}else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch(IOException e) {
				e.printStackTrace();
			}
			if(buflen <= 0) {
				return false;
			}
		}
		return true;
	}

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

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

	private void skipUnprintable() {
		while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
	}

	public boolean hasNext() {
		skipUnprintable();
		return hasNextByte();
	}

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

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

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

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

Score : 100 points

Problem Statement

Snuke prepared 6 problems for a upcoming programming contest.
For each of those problems, Rng judged whether it can be used in the contest or not.

You are given a string S of length 6.
If the i-th character of s is 1, it means that the i-th problem prepared by Snuke is accepted to be used; 0 means that the problem is not accepted.

How many problems prepared by Snuke are accepted to be used in the contest?

Constraints

The length of S is 6.

S consists of 0 and 1.

Inputs

Input is given from Standard Input in the following format:

S

Outputs

Print the number of problems prepared by Snuke that are accepted to be used in the contest.

Sample Input 1

111100

Sample Output 1

4

The first, second, third and fourth problems are accepted, for a total of four.

Sample Input 2

001001

Sample Output 2

2

Sample Input 3

000000

Sample Output 3

0


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

		System.out.println(N*N-A);
	}
}

Score : 100 points

Problem Statement

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a 3 \times 3 square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Scanner;

class Main {
    static final int MOD = 1000000007;
    static final int INF = 1 << 30;
    static final int ALF = 26;

    Main() {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int K = sc.nextInt();
        int ans = 0;
        int[] X = new int[N];
        for(int i=0;i<N;i++){
            X[i]=sc.nextInt();
            ans+=Math.min(X[i],K-X[i])*2;
        }
        System.out.println(ans);
    }

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

Score : 200 points

Problem Statement

There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i).
Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N.

In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th type-B robot at coordinates (K, i).
Thus, now we have one type-A robot and one type-B robot on each of the N lines y = 1, y = 2, ..., y = N.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates (0, a), it will move to the position of the ball on the line y = a, collect the ball, move back to its original position (0, a) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates (K, b), it will move to the position of the ball on the line y = b, collect the ball, move back to its original position (K, b) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Snuke will activate some of the 2N robots to collect all of the balls. Find the minimum possible total distance covered by robots.

Constraints

1 \leq N \leq 100

1 \leq K \leq 100

0 < x_i < K

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
K
x_1 x_2 ... x_N

Outputs

Print the minimum possible total distance covered by robots.

Sample Input 1

1
10
2

Sample Output 1

4

There are just one ball, one type-A robot and one type-B robot.

If the type-A robot is used to collect the ball, the distance from the robot to the ball is 2, and the distance from the ball to the original position of the robot is also 2, for a total distance of 4.

Similarly, if the type-B robot is used, the total distance covered will be 16.

Thus, the total distance covered will be minimized when the type-A robot is used. The output should be 4.

Sample Input 2

2
9
3 6

Sample Output 2

12

The total distance covered will be minimized when the first ball is collected by the type-A robot, and the second ball by the type-B robot.

Sample Input 3

5
20
11 12 9 17 12

Sample Output 3

74


public class Main {
	int a;
	int b;
	int c;
	int d;
	int e;
	int f;

	public static void main(String[] args) {
		java.util.Scanner s = new java.util.Scanner(System.in);
		System.out.println(Main.calc(s.nextInt(), s.nextInt(), s.nextInt(),
				s.nextInt(), s.nextInt(), s.nextInt()));
	}

	public Main(int a, int b, int c, int d, int e, int f) {
		this.a = a;
		this.b = b;
		this.c = c;
		this.d = d;
		this.e = e;
		this.f = f;
	}

	public static String calc(int a, int b, int c, int d, int e, int f) {
		return new Main(a, b, c, d, e, f).calc();
	}

	public String calc() {
		double noudo = 0;
		int satousui = 0;
		int satou = 0;
		for (int i = 0; this.sum(i, 0, 0, 0) <= f; i++) {
			for (int j = 0; this.sum(i, j, 0, 0) <= f; j++) {
				for (int k = 0; this.sum(i, j, k, 0) <= f; k++) {
					for (int l = 0; this.sum(i, j, k, l) <= f; l++) {
						double cal = this.calcNoudo(i, j, k, l);
						if (this.isTokeru(i, j, k, l) && noudo < cal) {
							noudo = cal;
							satousui = this.sum(i, j, k, l);
							satou = c * k + d * l;
						}
					}
				}
			}
		}
		return satousui + " " + satou;
	}

	public int sum(int i, int j, int k, int l) {
		return 100 * i * a + 100 * j * b + k * c + l * d;
	}

	public double calcNoudo(int i, int j, int k, int l) {
		if ((100 * (i * a + j * b) + k * c + l * d) <= 0) {
			return 0;
		}
		return 100 * (k * c + l * d) / (100 * (i * a + j * b) + k * c + l * d);
	}

	public boolean isTokeru(int i, int j, int k, int l) {
		return (i * a + j * b) * e >= k * c + d * l;
	}

}

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


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

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());
      int C = Integer.parseInt(sc.next());
      int D = Integer.parseInt(sc.next());
      int E = Integer.parseInt(sc.next());
      int F = Integer.parseInt(sc.next());
      int[] res = new int[3];
      int a = 100*A;
      int b = 100*B;
      for(int i = 0; i<30; i++){
        if(a*i > F) break;
        for(int j = 0; j<30; j++){
            int w = a*i+b*j;
            if(w == 0) continue;
            if(w > F) break;
            else{
                int lim = w*E/100;
                for(int k = 0; k<lim; k++){
                  for(int l = 0; l<lim; l++){
                    int s = k+j;
                      if(s>lim) break;
                      if(s<=lim && w+s <= F){
                        int noudo = s*100/(s+w);
                          if(res[2]<=noudo){
                            //System.out.println("i,j,k,l = "+i+" "+j+" "+k+" "+l);
                            res[0] = s+w;
                            res[1] = s;
                            res[2] = noudo;
                          }
                      }
                  }
                }
            }
        }
      }
      System.out.println(res[0]+" "+res[1]);
  }
}


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

public class Main {

    static class Edge implements Comparable<Edge>{
        int start;
        int end;
        int weight;
        public Edge(int start, int end, int weigth) {
            this.start = start;
            this.end = end;
            this.weight = weigth;
        }

        @Override
        public int compareTo(Edge o) {
            return Integer.compare(this.weight, o.weight);
        }

    }

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

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                graph[i][j] = sc.nextInt();
            }
        }

        if (!legitGraph(graph)) {
            System.out.println(-1);
            return;
        } else {
            System.out.println(MST(graph));
            return;
        }

    }

    private static boolean legitGraph(int[][] graph) {
        int N = graph.length;
        for (int k = 0; k < N; k++) {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    if (graph[i][j] > graph[i][k] + graph[k][j]) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    private static int MST(int[][] graph) {
        PriorityQueue<Edge> pq = new PriorityQueue<>();
        Set<Integer> vertices = new HashSet<>();
        Set<Edge> edges = new HashSet<>();
        for (int i = 0; i < graph.length; i++) {
            for (int j = i + 1; j < graph.length; j++) {
                pq.add(new Edge(i, j, graph[i][j]));
            }
        }

        while(edges.size() < graph.length - 1) {
            edges.add(pq.remove());
        }

        int ans = 0;
        for (Edge edge : edges) {
            System.out.println(edge.start + " " + edge.end + " " + edge.weight);
            ans += edge.weight;
        }

        return ans;
    }
}

Score : 500 points

Problem Statement

In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.

Constraints

1 \leq N \leq 300

If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.

City 2 and City 3 is connected by a road of length 2.

City 3 and City 1 is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length 1 from City 1 to City 2 and City 2 to City 3, there is a path of length 2 from City 1 to City 3.
However, according to the table, the shortest distance between City 1 and City 3 must be 3.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000


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

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

    static class ASeptember9 {
        private static final String YES = "Yes";
        private static final String NO = "No";

        public void solve(int testNumber, LightScanner in, PrintWriter out) {
            int n = in.ints();
            out.println(n / 10 == 9 || n % 10 == 9 ? YES : NO);
        }

    }

    static class LightScanner {
        private BufferedReader reader = null;
        private StringTokenizer tokenizer = null;

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

        public String string() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ints() {
            return Integer.parseInt(string());
        }

    }
}

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


import java.util.*;
public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    Set<Integer> set = new HashSet<Integer>();
    for(int i = 0; i < N; i++){
        int A = sc.nextInt();
        if(set.contains(A)){
            set.remove(A);
        }else{
            set.add(A);
        }
    }
    System.out.println(set.size());

  }
}

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.

Then, you are asked a question: How many numbers are written on the sheet now?

The numbers announced by Joisino are given as A_1, ... ,A_N in the order she announces them. How many numbers will be written on the sheet at the end of the game?

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print how many numbers will be written on the sheet at the end of the game.

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

6 is not written on the sheet, so write 6.

2 is not written on the sheet, so write 2.

6 is written on the sheet, so erase 6.

Thus, the sheet contains only 2 in the end. The answer is 1.

Sample Input 2

4
2
5
5
2

Sample Output 2

0

It is possible that no number is written on the sheet in the end.

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeSet;

import org.omg.Messaging.SyncScopeHelper;

public class Main {
	Scanner sc = new Scanner(System.in);
	public static void main(String[] args){
		new Main();
	}
	public Main(){
		new Test_100().doIt();
	}
	class Test_100{
		void doIt() {
			int X = sc.nextInt();
			int T = sc.nextInt();
			int ans = X - T;
			if(ans < 0)System.out.println(0);
			else System.out.println(ans);
		}
	}
}

Score : 100 points

Problem Statement

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Sample Input 1

100 17

Sample Output 1

83

17 out of the initial 100 grams of sand will be consumed, resulting in 83 grams.

Sample Input 2

48 58

Sample Output 2

0

All 48 grams of sand will be gone, resulting in 0 grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0


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

		if (X-t > 0) System.out.println(X-t);
		else if (X-t <= 0) System.out.println("0");
	}
}


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

public class Main {

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;
    final long MOD = 1000L * 1000L * 1000L + 7;

    void solveA() throws IOException {
        int x = nextInt();
        int t = nextInt();
        outln(Math.max(0, x - t));
    }
    void solveB() throws IOException {

    }
    void solveC() throws IOException {

    }
    void solveD() throws IOException {

    }

    void shuffle(int[] a) {
        int n = a.length;
        for(int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            int tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }
    private void outln(Object o) {
        out.println(o);
    }
    private void out(Object o) {
        out.print(o);
    }
    public Main() throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);

        solveA();

        out.close();
    }
    public static void main(String[] args) throws IOException {
        new Main();
    }

    public long[] nextLongArr(int n) throws IOException{
        long[] res = new long[n];
        for(int i = 0; i < n; i++)
            res[i] = nextLong();
        return res;
    }
    public int[] nextIntArr(int n) throws IOException {
        int[] res = new int[n];
        for(int i = 0; i < n; i++)
            res[i] = nextInt();
        return res;
    }
    public String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
            }
        }
        return st.nextToken();
    }
    public String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;
        }
    }
    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}


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

public class Main {

	public static void main (String[] args) {
	   InputReader in = new InputReader(System.in);
	   int n = in.readInt();
	   int arr[] = new int[100003];
	   for(int i = 0; i<n; i++) {
		   int a = in.readInt();
		   if(a != 0) {
			  arr[a-1]++;
		   }
			   arr[a]++;
			   arr[a+1]++;
	   }
	   int max = 0;
	   for(int i : arr) {
		 max = Math.max(max, i);
	   }
	   System.out.println(max);
	}
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

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

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

	public int readInt() {
		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 String readString() {
		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 readLong() {
		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 boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

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

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

Score : 300 points

Problem Statement

You are given an integer sequence of length N, a_1,a_2,...,a_N.

For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.

After these operations, you select an integer X and count the number of i such that a_i=X.

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

0≤a_i<10^5 (1≤i≤N)

a_i is an integer.

Input

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

N
a_1 a_2 .. a_N

Output

Print the maximum possible number of i such that a_i=X.

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1