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

public class Main {

	private static Scanner sc;
	private static Printer pr;

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

		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}
		long[] cumsum = new long[n + 1];
		for (int i = 0; i < n; i++) {
			cumsum[i + 1] = cumsum[i] + a[i];
		}

		final long INF = Long.MAX_VALUE / 2;
		long[][] dp = new long[n][n];
		for (int d = 1; d < n; d++) {
			for (int i = 0; i < n; i++) {
				for (int j = i + d; j < n; j++) {
					dp[i][j] = INF;
					for (int k = i; k < j; k++) {
						dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + cumsum[k + 1] - cumsum[i] + cumsum[j + 1] - cumsum[k + 1]);
					}
				}
			}
		}

		pr.println(dp[0][n - 1]);
	}

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

		solve();

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

	static String INPUT = null;

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

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

Score : 100 points

Problem Statement

There are N slimes lining up in a row.
Initially, the i-th slime from the left has a size of a_i.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.util.stream.Stream;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
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);
        LightWriter out = new LightWriter(outputStream);
        OMatching solver = new OMatching();
        solver.solve(1, in, out);
        out.close();
    }

    static class OMatching {
        private static final int MOD = (int) 1e9 + 7;

        public void solve(int testNumber, LightScanner in, LightWriter out) {
            int n = in.ints(), all = 1 << n;
            int[][] a = in.ints(n, n);

            long[] dp = new long[all];
            dp[0] = 1;
            for (int j = 0; j < all - 1; j++) {
                int i = Integer.bitCount(j);
                for (int k = 0; k < n; k++) {
                    int b = 1 << k;
                    if (a[i][k] == 0 || (b & j) != 0) continue;
                    dp[b | j] += dp[j];
                    if (dp[b | j] >= MOD) dp[b | j] -= MOD;
                }
            }
            out.ans(dp[all - 1]).ln();
        }

    }

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

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

        public String string() {
            while (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 int[] ints(int length) {
            return IntStream.range(0, length).map(x -> ints()).toArray();
        }

        public int[][] ints(int height, int width) {
            return IntStream.range(0, height).mapToObj(x -> ints(width)).toArray(int[][]::new);
        }

        public void close() {
            try {
                this.reader.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }

    }

    static class LightWriter implements AutoCloseable {
        private final Writer out;
        private boolean autoflush = false;
        private boolean breaked = true;

        public LightWriter(Writer out) {
            this.out = out;
        }

        public LightWriter(OutputStream out) {
            this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
        }

        public LightWriter print(char c) {
            try {
                out.write(c);
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter print(String s) {
            try {
                out.write(s, 0, s.length());
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter ans(String s) {
            if (!breaked) {
                print(' ');
            }
            return print(s);
        }

        public LightWriter ans(long l) {
            return ans(Long.toString(l));
        }

        public LightWriter ln() {
            print(System.lineSeparator());
            breaked = true;
            if (autoflush) {
                try {
                    out.flush();
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            }
            return this;
        }

        public void close() {
            try {
                out.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }

    }
}

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

Score : 100 points

Problem Statement

There are N men and N women, both numbered 1, 2, \ldots, N.

For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}.
If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not.

Taro is trying to make N pairs, each consisting of a man and a woman who are compatible.
Here, each man and each woman must belong to exactly one pair.

Find the number of ways in which Taro can make N pairs, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 21

a_{i, j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of ways in which Taro can make N pairs, modulo 10^9 + 7.

Sample Input 1

3
0 1 1
1 0 1
1 1 1

Sample Output 1

3

There are three ways to make pairs, as follows ((i, j) denotes a pair of Man i and Woman j):

(1, 2), (2, 1), (3, 3)

(1, 2), (2, 3), (3, 1)

(1, 3), (2, 1), (3, 2)

Sample Input 2

4
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0

Sample Output 2

1

There is one way to make pairs, as follows:

(1, 2), (2, 4), (3, 1), (4, 3)

Sample Input 3

1
0

Sample Output 3

0

Sample Input 4

21
0 0 0 0 0 0 0 1 1 0 1 1 1 1 0 0 0 1 0 0 1
1 1 1 0 0 1 0 0 0 1 0 0 0 0 1 1 1 0 1 1 0
0 0 1 1 1 1 0 1 1 0 0 1 0 0 1 1 0 0 0 1 1
0 1 1 0 1 1 0 1 0 1 0 0 1 0 0 0 0 0 1 1 0
1 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0
0 1 1 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 0 0 1
0 1 0 0 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 1 0
0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1
0 0 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1
0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1
0 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0
0 0 1 0 0 1 1 1 1 0 1 1 0 1 1 1 0 0 0 0 1
0 1 1 0 0 1 1 1 1 0 0 0 1 0 1 1 0 1 0 1 1
1 1 1 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 0 1
0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1
1 0 1 1 0 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 0
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 0 1
0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 1 0 1
0 0 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0
1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 0
1 0 0 1 1 0 1 1 1 1 1 0 1 0 1 1 0 0 0 0 0

Sample Output 4

102515160

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

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.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.stream.IntStream;

public class Main {

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

	public Main() {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt(), h[] = sc.nextInt(N), a[] = sc.nextInt(N);
		LazySegmentTree<Long, Long> segment = new LazySegmentTree<Long, Long>(IntStream.range(0, N).mapToObj(i -> new Long(0)).toArray(Long[]::new), new Maximum<Long>(), new Maximum<Long>(), new Maximum<Long>());
		for (int i = 0;i < N;++ i) segment.update(a[i] + segment.get(0, h[i]), h[i] - 1);
		System.out.println(segment.get(0, N));
	}

	public class Maximum<T extends Comparable<T>> implements Monoid<T>, Commutative<T>, LazySegmentInterface<T, T>{

		@Override
		public T operate(T left, T right) {
			if (left == null) return right;
			else if (right == null) return left;
			return left.compareTo(right) > 0 ? left : right;
		}

		@Override
		public T unit() {
			return null;
		}

		@Override
		public T function(T element, T reaction, int N) {
			return operate(element, reaction);
		}

	}

	public interface Commutative<T> {
	}

	public interface Monoid<T> extends Associative<T>, Unit<T> {
	}

	public interface Unit<T> {
		public T unit();
	}

	public interface Associative<T> {
		public T operate(T left, T right);
	}

	public interface LazySegmentInterface<T, E> {
		public T function(T element, E reaction,  int N);
	}

	public class LazySegmentTree<T, E> {
		private Associative<T> semigroup;
		private Associative<E> lazygroup;
		private LazySegmentInterface<T, E> operate;
		private T dat[];
		private E lazy[];
		private int size;

		public LazySegmentTree(T[] dat, Associative<T> semigroup, Associative<E> lazygroup, LazySegmentInterface<T, E> operate) {
			this.semigroup = semigroup;
			this.lazygroup = lazygroup;
			this.operate = operate;
			build(dat);
		}

		@SuppressWarnings("unchecked")
		private void build(T dat[]) {
			size = dat.length;
			this.dat = (T[]) new Object[Math.max(2, Integer.highestOneBit(dat.length - 1) << 2)]; // 要素数を超える最小の2冪*2
			this.lazy = (E[]) new Object[this.dat.length]; // その遅延評価に使う関数
			System.arraycopy(dat, 0, this.dat, this.dat.length >> 1, dat.length); // 最下段を埋める
			for (int i = this.dat.length / 2 - 1;i > 0; -- i) this.dat[i] = operate(this.dat[i << 1], this.dat[i * 2 + 1]); // 最下段以外すべて、下から埋める
		}

		public void debug() {
			System.out.print("data : ");
			for (T i : dat) System.out.print(i + " ");
			System.out.println();
			System.out.print("lazy : ");
			for (E i : lazy) System.out.print(i + " ");
			System.out.println();
		}

		private void lazy(int n, int length) {
			lazy[n << 1] = lazygroup.operate(lazy[n], lazy[n << 1]);
			lazy[n * 2 + 1] = lazygroup.operate(lazy[n], lazy[n * 2 + 1]);
			getLazy(n, length);
		}

		private T operate(T left, T right) {
			if (right == null) return left; // 右がnullの可能性の方がはるかに高いので
			else if (left == null) return right;
			else return semigroup.operate(left, right);
		}

		private void lazyUpdate(E lazy, int index, int length) {
			this.lazy[index] = lazyoperate(this.lazy[index], lazy);
			dat[index] = operate.function(dat[index], this.lazy[index], length);
		}

		private E lazyoperate(E left, E right) {
			if (right == null) return left; // 右がnullの可能性の方がはるかに高いので
			else if (left == null) return right;
			else return lazygroup.operate(left, right);
		}

		private T getLazy(int index, int length) {
			dat[index] = operate.function(dat[index], lazy[index], length);
			lazy[index] = null;
			return dat[index];
		}

		public void update(E dat, int index) {
			update(dat, index, index + 1);
		}

		public void update(E dat, int left, int right) {
			if (left >= right || right > size) throw new IllegalArgumentException("[" + left + ", " + right + ") is undefined.");
			int mid = left ^ right, m = 1, l, r, length = this.dat.length >> 1;
			for (;(mid & length) == 0;m <<= 1, length >>= 1) {
				if ((left & length) != 0) {
					left &= ~length;
					right &= ~length;
					++ m;
				}
				lazy(m, length); // 境界を見つけるまで遅延評価
			}
			l = m;
			int lengthL = length;
			while(left != 0) { // 左側評価開始
				lazy(l, lengthL);
				lengthL >>= 1;
				l <<= 1;
				if ((left & lengthL) == 0) { // 1個右は含まれる区間なので
					lazyUpdate(dat, l + 1, lengthL);
				} else {
					left &= ~lengthL;
					++ l;
				}
			}
			lazyUpdate(dat, l, lengthL);
			r = m + 1;
			int lengthR = length;
			right &= ~lengthR;
			while(right != 0) { // 右側評価開始
				lazy(r, lengthR);
				lengthR >>= 1;
				r <<= 1;
				if ((right & lengthR) != 0) { // 1個左は含まれる区間なので
					right &= ~lengthR;
					lazyUpdate(dat, r, lengthR);
					++ r;
				}
			}
			// これで全ての遅延評価が終わったので、次は戻していく操作
			while(l > m) {
				l >>= 1;
				lengthL <<= 1;
				this.dat[l] = operate(this.dat[l << 1], this.dat[l * 2 + 1]);
			}
			while(r > m + 1) {
				r >>= 1;
				lengthR <<= 1;
				lazy(r, lengthR);
				this.dat[r] = operate(this.dat[r << 1], this.dat[r * 2 + 1]);
			}
			while(m > 1) {
				m >>= 1;
				length <<= 1;
				lazy(m, length);
				this.dat[m] = operate(this.dat[m << 1], this.dat[m * 2 + 1]);
			}
		}

		public T get(int index) {
			return get(index, index + 1);
		}

		public T get(int left, int right) {
			if (left >= right || right > size) throw new IllegalArgumentException("[" + left + ", " + right + ") is undefined.");
			int mid = left ^ right, i = 1, j, length = this.dat.length >> 1;
			T ret = null;
			for (;(mid & length) == 0;i <<= 1, length >>= 1) { // 境界を見つけるまで遅延評価
				if ((left & length) != 0) {
					left &= ~length;
					right &= ~length;
					++ i;
				}
				lazy(i, length);
			}
			j = i + 1;
			int lengthL = length;
			while(left != 0) { // 左側評価開始
				lazy(i, lengthL);
				lengthL >>= 1;
				i <<= 1;
				if ((left & lengthL) == 0) { // 1個右は含まれる区間なので
					ret = operate(getLazy(i + 1, lengthL), ret);
				} else {
					left &= ~lengthL;
					++ i;
				}
			}
			ret = operate(getLazy(i, lengthL), ret);
			int lengthR = length;
			right &= ~lengthR;
			while(right != 0) { // 右側評価開始
				lazy(j, lengthR);
				lengthR >>= 1;
				j <<= 1;
				if ((right & lengthR) != 0) { // 1個左は含まれる区間なので
					right &= ~lengthR;
					ret = operate(ret, getLazy(j++, lengthR));
					++ j;
				}
			}
			return ret;
		}
	}

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

		public int[] nextInt(int width) {
			int[] ret = new int[width];
			for (int i = 0;i < width;++ i) ret[i] = nextInt();
			return ret;
		}

		public long[] nextLong(int width) {
			long[] ret = new long[width];
			for (int i = 0;i < width;++ i) ret[i] = nextLong();
			return ret;
		}

		public int[][] nextInt(int width, int height) {
			int[][] ret = new int[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextInt();
			return ret;
		}

		public long[][] nextLong(int width, int height) {
			long[][] ret = new long[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong();
			return ret;
		}
	}

}

Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

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

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.


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

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

    long M = 1_000_000_007L;
    int H = scanner.nextInt();
    int W = scanner.nextInt();
    int N = scanner.nextInt() + 1;
    Wall[] w = new Wall[N + 1];
    w[0] = new Wall(1, 1);
    for (int i = 1; i <= N - 1; i++) {
      w[i] = new Wall(scanner.nextInt(), scanner.nextInt());
    }
    w[N] = new Wall(H, W);

    Arrays.sort(w, (w1, w2) -> {
      if (w1.r <= w2.r && w1.c <= w2.c) return -1;
      if (w1.r >= w2.r && w1.c >= w2.c) return 1;
      return 0;
    });

    long[] fact = new long[H + W + 1];
    long[] factinv = new long[H + W + 1];
    fact[0] = 1;
    for (int i = 0; i < H + W; i++) fact[i + 1] = fact[i] * (i + 1) % M;
    factinv[0] = 1;
    for (int i = 1; i <= H + W; i++) factinv[i] = factinv[i - 1] * inverse(i, M) % M;

    long[][] dp = new long[N + 1][N + 1];
    dp[0][0] = 1;
    for (int i = 1; i <= N; i++) {
      for (int j = 1; j <= i; j++) {
        for (int k = j - 1; k < i; k++) {
          int dr = w[i].r - w[k].r;
          int dc = w[i].c - w[k].c;
          dp[i][j] += dp[k][j - 1] * comb(fact, factinv, dr + dc, dr, M) % M;
          if (dp[i][j] >= M) dp[i][j] -= M;
        }
      }
    }

    long res = 0;
    for (int i = 0; i <= N; i++) {
      res += dp[N][i] * (i % 2 == 0 ? -1 : 1);
      if (res >= M) res -= M;
      if (res < 0) res += M;
    }
    System.out.println(res);
  }

  private static long comb(long[] fact, long[] factinv, int n, int k, long M) {
    if (k < 0) return 0;
    if (n < k) return 0;
    long res = fact[n] * factinv[n - k] % M;
    res *= factinv[k];
    res %= M;
    return res;
  }

  public static long inverse(long a, long mod) {
    return modpow(a, mod - 2, mod);
  }

  public static long modpow(long a, long n, long mod) {
    long res = 1;
    while (n > 0) {
      if (n % 2 == 1) res = (res * a) % mod;
      a = (a * a) % mod;
      n >>= 1;
    }
    return res % mod;
  }

  private static class Wall {
    public final int r;
    public final int c;

    private Wall(int r, int c) {
      this.r = r;
      this.c = c;
    }
  }
}

Score : 100 points

Problem Statement

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

In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

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

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

Constraints

All values in input are integers.

2 \leq H, W \leq 10^5

1 \leq N \leq 3000

1 \leq r_i \leq H

1 \leq c_i \leq W

Squares (r_i, c_i) are all distinct.

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

Input

Input is given from Standard Input in the following format:

H W N
r_1 c_1
r_2 c_2
:
r_N c_N

Output

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

Sample Input 1

3 4 2
2 2
1 4

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2 2
2 1
4 2

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5 4
3 1
3 5
1 3
5 3

Sample Output 3

24

Sample Input 4

100000 100000 1
50000 50000

Sample Output 4

123445622

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


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

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

        int a = sc.nextInt(); // bad
        int b = sc.nextInt(); //good
        int c = sc.nextInt(); //good
        if (a + b >= c) {
            System.out.println(b + c); // all ok
        } else {
            System.out.println(b + (b + a) + 1);
        }

        sc.close();
    }
}

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

0 \leq A,B,C \leq 10^9

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.regex.Pattern;
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);
        LightWriter out = new LightWriter(outputStream);
        CColoringTorus solver = new CColoringTorus();
        solver.solve(1, in, out);
        out.close();
    }

    static class CColoringTorus {
        public void solve(int testNumber, LightScanner in, LightWriter out) {
            Debug.enable("src");
            int k = in.ints();
            int m = (k + 1) / 2;
            int n = m * 2;
            out.ans(n).ln();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    int v = (i + j) % m + 1;
                    if (i % 2 == 1 && v + m <= k) {
                        v += m;
                    }
                    out.ans(v);
                }
                out.ln();
            }
        }

    }

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

    }

    static class Debug {
        private static final String DEBUG_CALL_PATTERN = "^.+\\.debug\\((.+)\\);.*$";
        private static Pattern debugRegex;
        private static boolean enabled = false;
        private static String src;

        public static void enable(String s) {
            enabled = true;
            src = s;
            if (debugRegex == null) {
                debugRegex = Pattern.compile(DEBUG_CALL_PATTERN);
            }
        }

    }

    static class LightWriter implements AutoCloseable {
        private final Writer out;
        private boolean autoflush = false;
        private boolean breaked = true;

        public LightWriter(Writer out) {
            this.out = out;
        }

        public LightWriter(OutputStream out) {
            this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())));
        }

        public LightWriter print(char c) {
            try {
                out.write(c);
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter print(String s) {
            try {
                out.write(s, 0, s.length());
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter ans(String s) {
            if (!breaked) {
                print(' ');
            }
            return print(s);
        }

        public LightWriter ans(int i) {
            return ans(Integer.toString(i));
        }

        public LightWriter ln() {
            print(System.lineSeparator());
            breaked = true;
            if (autoflush) {
                try {
                    out.flush();
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            }
            return this;
        }

        public void close() {
            try {
                out.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }

    }
}

Score : 1000 points

Problem Statement

For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from the top and the (c+1)-th column from the left.
A good coloring of this grid using K colors is a coloring that satisfies the following:

Each square is painted in one of the K colors.

Each of the K colors is used for some squares.

Let us number the K colors 1, 2, ..., K. For any colors i and j (1 \leq i \leq K, 1 \leq j \leq K), every square in Color i has the same number of adjacent squares in Color j. Here, the squares adjacent to square (r, c) are ((r-1)\; mod\; n, c), ((r+1)\; mod\; n, c), (r, (c-1)\; mod\; n) and (r, (c+1)\; mod\; n) (if the same square appears multiple times among these four, the square is counted that number of times).

Given K, choose n between 1 and 500 (inclusive) freely and construct a good coloring of an n \times n grid using K colors.
It can be proved that this is always possible under the constraints of this problem,

Constraints

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K

Output

Output should be in the following format:

n
c_{0,0} c_{0,1} ... c_{0,n-1}
c_{1,0} c_{1,1} ... c_{1,n-1}
:
c_{n-1,0} c_{n-1,1} ... c_{n-1,n-1}

n should represent the size of the grid, and 1 \leq n \leq 500 must hold.
c_{r,c} should be an integer such that 1 \leq c_{r,c} \leq K and represent the color for the square (r, c).

Sample Input 1

2

Sample Output 1

3
1 1 1
1 1 1
2 2 2

Every square in Color 1 has three adjacent squares in Color 1 and one adjacent square in Color 2.

Every square in Color 2 has two adjacent squares in Color 1 and two adjacent squares in Color 2.

Output such as the following will be judged incorrect:

2
1 2
2 2

3
1 1 1
1 1 1
1 1 1

Sample Input 2

9

Sample Output 2

3
1 2 3
4 5 6
7 8 9


import java.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        AtCoder problem = new AtCoder(sc);
        problem.solve(sc, out);

        out.flush();
    }

}

class AtCoder {

    long N, P;

    AtCoder(FastScanner sc) {
        N = sc.nextLong();
        P = sc.nextLong();
    }

    void solve(FastScanner sc, PrintWriter out) {
        if (P == 1) {
            out.println(1);
            return;
        }
        List<Long> ls = primeFactorization(P);
        long ans = 1;
        for (int i = 1; i < ls.size(); i += 2) {
            if (ls.get(i) >= N) ans *= ls.get(i - 1) * (ls.get(i) / N);
        }
        out.println(ans);
    }

    List<Long> primeFactorization(long n) {
        List<Long> ls = new ArrayList<>();
        for (long i = 2; i * i <= n; i++) {
            if (n % i != 0) continue;
            long ex = 0;
            while (n % i == 0) {
                ex++;
                n /= i;
            }
            ls.add(i);
            ls.add(ex);
        }
        if (n != 1) {
            ls.add(n);
            ls.add(1L);
        }
        return ls;
    }
}

class FastScanner {

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

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

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

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

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

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

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

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

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

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

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

    public double[] arrayDouble(int N) {
        double[] array = new double[N];
        for (int i = 0; i < N; i++) {
            array[i] = nextDouble();
        }
        return array;
    }

    public String[] arrayString(int N) {
        String[] array = new String[N];
        for (int i = 0; i < N; i++) {
            array[i] = next();
        }
        return array;
    }

    public int randomInt() {
        Random r = new Random();
        int value = r.nextInt((int) 1e6);
        System.out.println(value);
        return value;
    }

    public int[] randomInt(int N) {
        int[] array = new int[N];
        Random r = new Random();
        for (int i = 0; i < N; i++) {
            array[i] = r.nextInt((int) 1e6);
        }
        System.out.println(Arrays.toString(array));
        return array;
    }

}

class My {

    static void ans(boolean b) {
        System.out.println(b ? "Yes" : "No");
    }

    static void ANS(boolean b) {
        System.out.println(b ? "YES" : "NO");
    }

    static String sort(String s) {
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        return String.valueOf(ch);
    }

    static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    static int[] reverse(int[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            int temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long[] reverse(long[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            long temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static double[] reverse(double[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            double temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static String[] reverse(String[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            String temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static char[] reverse(char[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            char temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long min(long... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static int min(int... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static double min(double... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static long max(long... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int max(int... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static double max(double... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int sum(long number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

}

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long n = sc.nextLong();
		long p = sc.nextLong();
		if(n==1) {
			System.out.println(p);
			return;
		}
		Map<Long,Long> sosuMap = new HashMap<Long,Long>();
		for(long i =2;i <= Math.sqrt(p);) {
			if(p % i == 0) {
				long sosuCount = 0;
				while(p % i == 0) {
					sosuCount++;
					p /= i;
				}
				sosuMap.put((long) i, sosuCount);
			}
			if(i ==2) {
				i++;
			}else {
				i+=2;
			}
		}

		long answer = 1;
		for(Map.Entry<Long, Long> entry:sosuMap.entrySet()) {
			if(entry.getValue() >= n) {
				answer *=Math.pow((double)entry.getKey(),(double)(entry.getValue() / n));

			}

		}

		System.out.println(answer);
	}

}


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

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

	// 1000
	// 1???
	// ?1?1
	// 0??1

	static void solve()
	{
		int n = ni(), m = ni();
		int[][] co = new int[m][];
		for(int i = 0;i < m;i++){
			co[i] = na(3);
		}
		Map<Long, Integer> map = new HashMap<>();
		for(int[] c : co){
			map.put((long)c[0]<<32|c[1], c[2]);
		}
		int[] udiag = new int[n-1];
		int[] ddiag = new int[n-1];
		int[] diag = new int[n];
		Arrays.fill(diag, -1);
		Arrays.fill(udiag, -1);
		Arrays.fill(ddiag, -1);

		int mod = 998244353;
		int free = 0;
		for(int i = 1;i <= n;i++){
			if(!map.containsKey((long)i<<32|i)){
			}else{
				diag[i-1] = map.get((long)i<<32|i);
			}
		}
		int np = 0;
		for(int i = 0;i < m;i++){
			int[] c = co[i];
			if(c[1] == c[0] + 1){
				udiag[c[0]-1] = c[2];
				continue;
			}else if(c[1] == c[0] - 1){
				ddiag[c[1]-1] = c[2];
				continue;
			}
			if(c[1] == c[0])continue;
			long inv = (long)c[1]<<32|c[0];
			if(map.containsKey(inv)){
				np += 1;
				int u = map.get(inv);
				if(u+c[2] == 1){
					if(Math.abs(c[0]-c[1]) > 2){
						out.println(0);
						return;
					}

					if(Math.abs(c[0]-c[1]) == 2){
						int r = (c[0]+c[1])/2;
						if(!map.containsKey((long)r<<32|r)){
							diag[r-1] = 1;
						}else{
							int q = map.get((long)r<<32|r);
							if(q == 0){
								out.println(0);
								return;
							}
						}
					}
				}
			}else{
				np += 2;
			}
		}
		free += (long)(n-1)*(n-2)/2-np/2;

//		tr(free);
//		tr(udiag);
//		tr(diag);
//		tr(ddiag);

		long[] dp = new long[2];
		if(diag[0] == 0){
			dp[0] = 1;
		}else if(diag[0] == 1){
			dp[1] = 1;
		}else{
			dp[0] = dp[1] = 1;
		}

		for(int i = 1;i < n;i++){
			{
				int fi = (udiag[i-1] >= 0 ? 1 : 0) + (ddiag[i-1] >= 0 ? 1 : 0);
				int fs = udiag[i-1] ^ ddiag[i-1];
				long[] ndp = new long[2];
				if(fi == 2){
					for(int j = 0;j < 2;j++){
						ndp[j^fs] += dp[j];
					}
				}else if(fi == 1){
					ndp[0] = (dp[0] + dp[1]) % mod;
					ndp[1] = (dp[0] + dp[1]) % mod;
				}else{
					ndp[0] = (dp[0] + dp[1])*2L % mod;
					ndp[1] = (dp[0] + dp[1])*2L % mod;
				}
				dp = ndp;
			}
			long[] ndp = new long[2];
			if(diag[i] == 0){
				ndp[0] = dp[0];
			}else if(diag[i] == 1){
				ndp[1] = dp[1];
			}else{
				ndp[0] = dp[0];
				ndp[1] = dp[1];
			}
			dp = ndp;
		}

		out.println((dp[0]+dp[1])%mod * pow(2, free, mod) % mod);
	}
	// ??1
	// ??1
	// 010

	public static long pow(long a, long n, long mod) {
		//		a %= mod;
		long ret = 1;
		int x = 63 - Long.numberOfLeadingZeros(n);
		for (; x >= 0; x--) {
			ret = ret * ret % mod;
			if (n << 63 - x < 0)
				ret = ret * a % mod;
		}
		return ret;
	}

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

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

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

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

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

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

	private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
//	private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

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

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

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

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

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

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

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

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

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

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

Score : 900 points

Problem Statement

Takahashi has an N \times N grid. The square at the i-th row and the j-th column of the grid is denoted by (i,j).
Particularly, the top-left square of the grid is (1,1), and the bottom-right square is (N,N).

An integer, 0 or 1, is written on M of the squares in the Takahashi's grid.
Three integers a_i,b_i and c_i describe the i-th of those squares with integers written on them: the integer c_i is written on the square (a_i,b_i).

Takahashi decides to write an integer, 0 or 1, on each of the remaining squares so that the condition below is satisfied.
Find the number of such ways to write integers, modulo 998244353.

For all 1\leq i < j\leq N, there are even number of 1s in the square region whose top-left square is (i,i) and whose bottom-right square is (j,j).

Constraints

2 \leq N \leq 10^5

0 \leq M \leq min(5 \times 10^4,N^2)

1 \leq a_i,b_i \leq N(1\leq i\leq M)

0 \leq c_i \leq 1(1\leq i\leq M)

If i \neq j, then (a_i,b_i) \neq (a_j,b_j).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
:
a_M b_M c_M

Output

Print the number of possible ways to write integers, modulo 998244353.

Sample Input 1

3 3
1 1 1
3 1 0
2 3 1

Sample Output 1

8

For example, the following ways to write integers satisfy the condition:

101 111
011 111
000 011

Sample Input 2

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

Sample Output 2

32

Sample Input 3

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

Sample Output 3

0

Sample Input 4

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

Sample Output 4

4

Sample Input 5

100000 0

Sample Output 5

342016343


import java.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        AtCoder problem = new AtCoder(sc);
        problem.solve(out);

        out.flush();
    }

}

class AtCoder {

    char[] S;

    AtCoder(FastScanner sc) {
        S = sc.next().toCharArray();
    }

    void solve(PrintWriter out) {
        int cnt = 0;
        long ans = 0;
        for (int i = 0; i < S.length; i++) {
            if (S[i] == 'W') {
                ans += i - cnt;
                cnt++;
            }
        }
        out.println(ans);
    }

}

class FastScanner {

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

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

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

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

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

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

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

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

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

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

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

    public double[] arrayDouble(int N) {
        double[] array = new double[N];
        for (int i = 0; i < N; i++) {
            array[i] = nextDouble();
        }
        return array;
    }

    public String[] arrayString(int N) {
        String[] array = new String[N];
        for (int i = 0; i < N; i++) {
            array[i] = next();
        }
        return array;
    }
}

class My {

    static void ans(boolean b) {
        System.out.println(b ? "Yes" : "No");
    }

    static void ANS(boolean b) {
        System.out.println(b ? "YES" : "NO");
    }

    static String sort(String s) {
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        return String.valueOf(ch);
    }

    static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    static int[] reverse(int[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            int temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long[] reverse(long[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            long temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static double[] reverse(double[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            double temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static String[] reverse(String[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            String temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static char[] reverse(char[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            char temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
        return array;
    }

    static long min(long... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static int min(int... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static double min(double... numbers) {
        Arrays.sort(numbers);
        return numbers[0];
    }

    static long max(long... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int max(int... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static double max(double... numbers) {
        Arrays.sort(numbers);
        return numbers[numbers.length - 1];
    }

    static int sum(long number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

}

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


import static java.lang.System.*;
import java.util.*;

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

        String s = sc.next();

		long ans = 0;
		long bc = 0;
		for(char c: s.toCharArray()) {
			if(c == 'B') bc++;
			else ans += bc;
		}

        out.println(ans);
    }
}


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

public class Main {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		for (int i = 0; i <= n - 1; i++) {
			a[i] = sc.nextInt();
		}
		Arrays.sort(a);

		a[n-1] = a[n-1]/2;
		int sum=0;
		for (int i = 0; i <= n - 1; i++) {
			sum+=a[i];
		}
		System.out.println(sum);
	}
}

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


import java.util.Scanner;

public class Main {

  public static int heightOfBurger(int level) {
    if (level == 0) {
      return 1;
    } else {
      return heightOfBurger(level - 1) * 2 + 3;
    }
  }

  public static int numberOfPatty(int level) {
    if (level == 0) {
      return 1;
    } else {
      return numberOfPatty(level - 1) * 2 + 1;
    }
  }

  public static int answer(int level, int layer) {
    if (layer == 1) {
      return 0;
    } else if (layer < heightOfBurger(level - 1) + 1) {
      return answer(level - 1, layer - 1);
    } else if (layer == heightOfBurger(level - 1) + 2) {
      return numberOfPatty(level - 1) + 1;
    } else if (layer < heightOfBurger(level - 1) * 2 + 2) {
      return numberOfPatty(level - 1) + 1 + answer(level - 1, layer - heightOfBurger(level - 1) - 2);
    } else {
      return numberOfPatty(level);
    }
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int level = sc.nextInt();
    int layer = sc.nextInt();
    System.out.println(answer(level, layer));
  }
}

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


import java.util.Scanner;

public class Main {

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		char[] c = s.toCharArray();
		int ans = 753;
		for (int i = 0; i < c.length - 2; i++) {
			int x = (c[i] - '0') * 100 + (c[i + 1] - '0') * 10 + (c[i + 2] - '0');
			ans = Math.min(ans, Math.abs(753 - x));
		}
		System.out.println(ans);
		sc.close();
	}
}

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

S is a string of length between 4 and 10 (inclusive).

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


import java.util.*;
import java.awt.*;
import static java.lang.System.*;
import static java.lang.Math.*;
public class Main {
    public static void main(String[]$){
        Scanner sc = new Scanner(in);
        int n=sc.nextInt();
        long k=0;
        if(n<357){
            out.println(0);
        }else{
            int order=2;
            for (int i = 357; i <= n; i++) {
                if(999<i&&i<10000)order=3;
                if(9999<i&&i<100000)order=4;
                if(99999<=i&&i<1000000)order=5;
                if(999999<i&&i<=10000000)order=6;
                if(9999999<i&&i<=100000000)order=7;
                if(99999999<i&&i<=1000000000)order=8;
                int ll=i%10;
                if(ll!=3&&ll!=5&&ll!=7)continue;
                int p=i/(int)power(10,order);/*
                out.println("i:"+i+" p:"+p+" ord:"+order);*/
                if(p!=3&&p!=5&&p!=7){
                //    out.println("i1"+i);
                    i=min((p+1)*(int)power(10,order),n);
                  //  out.println("i2"+i);
                }
                int n3=0,n5=0,n7=0;
                int c=0;
                int t=i;
                while(t>0){
                    int l=t%10;
                    if(l==3)++n3;
                    if(l==5)++n5;
                    if(l==7)++n7;
                    t/=10;
                    ++c;
                }
                if(n3+n5+n7==c&&n3>0&&n5>0&&n7>0){
                    ++k;
                }
            }
            out.println(k);
            }
        }
    static long power(long x,int n){
        long mod=1000000007;
        long ans=1;
        while (n>0) {
            if((n&1)==1){
                ans=(ans*x)%mod;
            }
            x=(x*x)%mod;
            n>>=1;
        }
        return ans;
    }
    //最大公約数
    static int gcd (int a, int b) {
        int temp;
        while((temp = a%b)!=0) {
            a = b;
            b = temp;
        }
        return b;
    }
//※最小公倍数はa*b/gcd(a,b)である
}

Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		IO io = new IO();
		int n = io.nextInt();
		int d = io.nextInt();
		HashMap<Integer,Integer> hm = new HashMap<>();
		for(int i=0;i<n;i++) {
			int x = io.nextInt();
			int y = io.nextInt();
			int h = (x % d) * 1000 + (y % d);
			int count = hm.getOrDefault(h, 0);
			hm.put(h, count + 1);
		}
		int l = 0;
		int r = 110000000;
		while(l + 1 < r) {
			int c = (l + r) / 2;
			if (check(n, d, hm, c)) {
				r = c;
			}else{
				l = c;
			}
		}
		System.out.println(r);
	}
	public static boolean check(int n, int d, HashMap<Integer,Integer> hm, long a) {
		int big = 0;
		for(int c : hm.values()) {
			while(big * big < c) {
				big++;
			}
		}
		LOOP: for(int x=0;x<d;x++) {
			HashSet<Integer> hs = new HashSet<>();
			for(Map.Entry<Integer,Integer> e: hm.entrySet()) {
				int p = e.getKey();
				int x2 = p / 1000;
				int y2 = p % 1000;
				int x3 = (x2 - x + d) % d;
				//int y3 = (y2 - y + d) % d;

				int count = e.getValue();
				long shorter = (int) Math.sqrt(count);
				long longer = shorter;
				if (shorter * longer < count) {
					longer++;
					if (shorter * longer < count) {
						shorter++;
					}
				}
				long x4l = x3 + d * (longer - 1);
				long x4s = x3 + d * (shorter - 1);
				if (x4s > a) {
					continue LOOP;
				}else if(x4l > a) {
					if (longer == big) {
						hs.add(y2);
					}
				}else{

				}
			}
			if (hs.size() <= 1) {
				return true;
			}
			ArrayList<Integer> al = new ArrayList<>(hs);
			al.sort(null);
			int max = al.get(0) - al.get(al.size()-1) + d;
			for(int i=0;i<al.size()-1;i++) {
				max = Math.max(al.get(i+1) - al.get(i), max);
			}
			if (d * big - max <= a) return true;
		}
		return false;
	}
}
class IO extends PrintWriter {
	private final InputStream in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	public IO() { this(System.in);}
	public IO(InputStream source) { super(System.out); this.in = source;}
	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		}else{
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}
	private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
	private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
	private static boolean isNewLine(int c) { return c == '\n' || c == '\r';}
	public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
	public boolean hasNextLine() { while(hasNextByte() && isNewLine(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 char[] nextCharArray(int len) {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		char[] s = new char[len];
		int i = 0;
		int b = readByte();
		while(isPrintableChar(b)) {
			if (i == len) {
				throw new InputMismatchException();
			}
			s[i++] = (char) b;
			b = readByte();
		}
		return s;
	}
	public String nextLine() {
		if (!hasNextLine()) {
			throw new NoSuchElementException();
		}
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while(!isNewLine(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 char nextChar() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		return (char) readByte();
	}
	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;}
	public double[] nextDoubleArray(int n) { double[] a = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a;}
	public void nextIntArrays(int[]... a) { for(int i=0;i<a[0].length;i++) for(int j=0;j<a.length;j++) a[j][i] = nextInt();}
	public int[][] nextIntMatrix(int n,int m) { int[][] a = new int[n][]; for(int i=0;i<n;i++) a[i] = nextIntArray(m); return a;}
	public char[][] nextCharMap(int n,int m) { char[][] a = new char[n][]; for(int i=0;i<n;i++) a[i] = nextCharArray(m); return a;}
	public void close() { super.close(); try {in.close();} catch (IOException e) {}}
}

Score : 800 points

Problem Statement

Niwango-kun, an employee of Dwango Co., Ltd., likes Niconico TV-chan, so he collected a lot of soft toys of her and spread them on the floor.

Niwango-kun has N black rare soft toys of Niconico TV-chan and they are spread together with ordinary ones. He wanted these black rare soft toys to be close together, so he decided to rearrange them.

In an infinitely large two-dimensional plane, every lattice point has a soft toy on it. The coordinates (x_i,y_i) of N black rare soft toys are given. All soft toys are considered to be points (without a length, area, or volume).

He may perform the following operation arbitrarily many times:

Put an axis-aligned square with side length D, rotate the square by 90 degrees with four soft toys on the four corners of the square. More specifically, if the left bottom corner's coordinate is (x, y), rotate four points (x,y) \rightarrow (x+D,y) \rightarrow (x+D,y+D) \rightarrow (x,y+D) \rightarrow (x,y) in this order. Each of the four corners of the square must be on a lattice point.

Let's define the scatteredness of an arrangement by the minimum side length of an axis-aligned square enclosing all black rare soft toys. Black rare soft toys on the edges or the vertices of a square are considered to be enclosed by the square.

Find the minimum scatteredness after he performs arbitrarily many operations.

Constraints

2 \leq N \leq 10^5

1 \leq D \leq 1000

0 \leq x_i, y_i \leq 10^9

Given coordinates are pairwise distinct

All numbers given in input are integers

Partial Scores

500 points will be awarded for passing the test set satisfying 1 \leq D \leq 30.

Input

Input is given from Standard Input in the following format:

N D
x_1 y_1
:
x_N y_N

Output

Print the answer.

Sample Input 1

3 1
0 0
1 0
2 0

Sample Output 1

1

Sample Input 2

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

Sample Output 2

4

Sample Input 3

8 3
0 0
0 3
3 0
3 3
2 2
2 5
5 2
5 5

Sample Output 3

4


import java.util.Scanner;

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

        int x = sc.nextInt();
        int y = sc.nextInt();

        System.out.println(x+(y/2));
    }
}

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


import java.util.*;

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

	public static void main(String[] args){
		int n = sc.nextInt();
		int m = sc.nextInt();
		int[] p = new int[m];
		int[] year = new int[m];
		StringBuilder[] y = new StringBuilder[m];

		for(int i = 0; i < m; ++i) {
			p[i] = sc.nextInt() - 1;
			year[i] = sc.nextInt();
			if(y[p[i]] == null) {
				y[p[i]] = new StringBuilder(String.valueOf(year[i]));
			}else{
				y[p[i]].append(':');
				y[p[i]].append(year[i]);
			}
		}

		String[][] ystr = new String[m][];
		for(int i = 0; i < m; ++i) {
			if(y[i] != null) {
				ystr[i] = y[i].toString().split(":");
				Arrays.sort(ystr[i]);
				y[i] = null;
			}
		}

		for(int i = 0; i < m; ++i) {
			String key = String.valueOf(year[i]);
			int index = Arrays.binarySearch(ystr[p[i]], key) + 1;
			System.out.printf("%06d%06d\n", p[i] + 1, index);
		}
	}
}

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


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

public class Main {
	public static void main(String[] args) {
		FastReader sc = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		int n = sc.nextInt();
		int m = sc.nextInt();

		Map<Integer, List<Long>> dic = new HashMap<>();
		List<Pair> toi = new ArrayList<>();
		for (int i = 0; i < m; i++) {
			int x = sc.nextInt();
			long y = sc.nextLong();
			toi.add(new Pair(x, y));
			List<Long> list = dic.getOrDefault(x, new ArrayList<>());
			list.add(y);
			dic.put(x, list);
		}

		Map<Integer, Long[]> sortDic = new HashMap<>();
		dic.entrySet().stream().forEach(e -> {
			Long[] tmp = e.getValue().toArray(new Long[e.getValue().size()]);
			Arrays.sort(tmp);
			sortDic.put(e.getKey(), tmp);
		});

		for (int i = 0; i < toi.size(); i++) {
			Pair mon = toi.get(i);
			String x = String.valueOf(mon.x);
			String paddingleft = x.format("%6s", x).replace(" ", "0");
			String index = String.valueOf(Arrays.binarySearch(sortDic.get(mon.x), mon.y) + 1);
			String paddingRight = index.format("%6s", index).replace(" ", "0");
			out.println(paddingleft + paddingRight);
		}

	}

	static class Pair {
		public int x;
		public long y;

		public Pair(int x, long y) {
			this.x = x;
			this.y = y;
		}
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

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

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

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

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

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


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	private static boolean ispf = false;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(
				new InputStreamReader(Main.class.getResourceAsStream("/data.txt")));
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] systemInLine = br.readLine().split(" ");
		int provinceCount = Integer.parseInt(systemInLine[0]);
		int cityCount = Integer.parseInt(systemInLine[1]);
		pf("辖区总数:" + provinceCount + " 城市总数:" + cityCount);

		/**
		 * 所有的城市
		 */

		//城市数组，0：省份，1：年份，2：输入顺序号，4：年份序号
		int[][]  proviceCityArray = new int[cityCount][4];

		for (int i = 0; i < cityCount; i++) {
			systemInLine = br.readLine().split(" ");
			int provinceIndex = Integer.parseInt(systemInLine[0]);
			int cityCreateYear = Integer.parseInt(systemInLine[1]);
			proviceCityArray[i][0]= provinceIndex;
			proviceCityArray[i][1]= cityCreateYear;
			proviceCityArray[i][2]= i+1;
		}
		br.close();

		/**
		 * 这次排序后辖区和年份已经排序了
		 */

		Arrays.sort(proviceCityArray,(o1, o2) -> (o1[0] == o2[0]) ? (o1[1] - o2[1]) : (o1[0] - o2[0]));

		for (int i = 0; i < proviceCityArray.length; i++) {
			if(i==0) {
				proviceCityArray[i][3] = 1;
			}else {
				if((proviceCityArray[i][0] == proviceCityArray[i - 1][0])) {//于上一次比较
					proviceCityArray[i][3] = proviceCityArray[i - 1][3] + 1;
				}else {
					proviceCityArray[i][3] = 1;
				}
			}
		}

		/**
		 * 再次排序拍会回来
		 */
		 Arrays.sort(proviceCityArray, (o1, o2) -> o1[2] - o2[2]);

		for (int i = 0; i < proviceCityArray.length; i++) {
			System.out.println(String.format("%06d", proviceCityArray[i][0])+String.format("%06d", proviceCityArray[i][3]));
		}

	}

	public static void pf(String s) {
		if (ispf) {
			System.out.println(s);
		}
	}
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
	@SuppressWarnings("resource")
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int m=scanner.nextInt();
		int p[]=new int[m];
		int y[]=new int[m];
		Map<Integer,List<Integer>>map=new TreeMap<>();
		for(int i=0;i<m;i++) {
			p[i]=scanner.nextInt();
			y[i]=scanner.nextInt();
			if (map.containsKey(p[i])) {
				map.get(p[i]).add(y[i]);
				Collections.sort(map.get(p[i]), new IComparator());
			} else {
				List<Integer>list=new ArrayList<>();
				list.add(y[i]);
				map.put(p[i], list);
			}
		}
		/*for(List<Integer> list:map.values()) {
			Collections.sort(list);
		}*/
		for(int i=0;i<m;i++) {
			int ind=lower_bound(map.get(p[i]), y[i])+2;
			System.out.printf("%06d", p[i]);
			System.out.printf("%06d", ind);
			System.out.println("");

		}
	}
	private static int lower_bound(List<Integer> list, int val) {
		return ~Collections.binarySearch(list, val, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1) - 1;
	}
}

class IComparator implements Comparator<Integer> {
	@Override
	public int compare(Integer o1, Integer o2) {
		if (o1 > o2) {
			return 1;
		} else if (o1 < o2) {
			return -1;
		} else {
			return 0;
		}
	}
}


import java.util.*;
import java.awt.*;
import static java.lang.System.*;
import static java.lang.Math.*;
//Loopで使う文字列の長さは固定！
//intで大丈夫？オーバーフローしない？
//Loop回数は本当に10⁹以内になってる？Loopは回る？？
public class Main {
    public static void main(String[]$){
        Scanner sc = new Scanner(in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        int[] p=new int[m];
        int[] y=new int[m];
        HashMap<Integer,Integer> map=new HashMap<>();
        HashMap<Integer,Integer> YtoM=new HashMap<>();
        TreeMap<Integer,Integer> tm=new TreeMap<>();
        for (int i = 0; i < m; i++) {
            p[i]=sc.nextInt();
            y[i]=sc.nextInt();
            tm.put(y[i],p[i]);
            map.put(p[i],1);
            YtoM.put(y[i],i);
        }
        String[] ans=new String[m];
        for(int k:tm.keySet()){
            String left="";
            String right="";
            left=Integer.toString(tm.get(k));
            int length=left.length();
            for (int i = 0; i <6-length; i++) {
                left="0"+left;
            }
            right=Integer.toString(map.get(tm.get(k)));
            length=right.length();
            for (int i = 0; i <6-length; i++) {
                right="0"+right;
            }
            map.put(tm.get(k),map.get(tm.get(k))+1);
            ans[YtoM.get(k)]=left+right;
        }
        for (int i = 0; i < m; i++) {
            out.println(ans[i]);
        }
    }
}


Score : 600 points

Problem Statement

There are N blocks arranged in a row, numbered 1 to N from left to right.
Each block has a weight, and the weight of Block i is A_i.
Snuke will perform the following operation on these blocks N times:

Choose one block that is still not removed, and remove it.
The cost of this operation is the sum of the weights of the blocks that are connected to the block being removed (including itself).
Here, two blocks x and y ( x \leq y ) are connected when, for all z ( x \leq z \leq y ), Block z is still not removed.

There are N! possible orders in which Snuke removes the blocks.
For all of those N! orders, find the total cost of the N operations, and calculate the sum of those N! total costs.
As the answer can be extremely large, compute the sum modulo 10^9+7.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For all of the N! orders, find the total cost of the N operations, and print the sum of those N! total costs, modulo 10^9+7.

Sample Input 1

2
1 2

Sample Output 1

9

First, we will consider the order "Block 1 -> Block 2".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 2, as only Block 2 remains.
Thus, the total cost of the two operations for this order is 3+2=5.

Then, we will consider the order "Block 2 -> Block 1".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 1, as only Block 1 remains.
Thus, the total cost of the two operations for this order is 3+1=4.

Therefore, the answer is 5+4=9.

Sample Input 2

4
1 1 1 1

Sample Output 2

212

Sample Input 3

10
1 2 4 8 16 32 64 128 256 512

Sample Output 3

880971923


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		ProblemB solver = new ProblemB();
		solver.solve(1, in, out);
		out.close();
	}

	static class ProblemB {
		final int N = 200010;
		final int MOD = (int) (1e9 + 7);
		int[] fact = new int[N];
		int[] inv = new int[N];
		int[] invFact = new int[N];

		public void solve(int testNumber, FastScanner in, PrintWriter out) {
			precalc();

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

			long[] f = new long[n];
			for (int d = 0; d < n; d++) {
				int b = n - 1 - d;
				long cur = 0;
				for (int k = 0; k <= b; k++) {
					long v = 1;
					v = v * fact[n - k - 1] % MOD;
					v = v * invFact[b - k] % MOD;
					cur = (cur + v) % MOD;
				}
				f[d] = cur * fact[b] % MOD;
			}

			long ans = 0;
//		for (int i = 0; i < n; i++) {
//			for (int j = 0; j < n; j++) {
//				ans = (ans + f[Math.abs(i - j)] * a[i]) % MOD;
//			}
//		}

			long[] inc = new long[n + 1];
			for (int i = 0; i < n; i++) {
				addSegment(inc, 0, 0, a[i]);
				addSegment(inc, 1, i, a[i]);
				addSegment(inc, 1, n - i - 1, a[i]);
			}

			long sum = 0;
			for (int i = 0; i < n; i++) {
				sum += inc[i];
				ans = (ans + sum * f[i]) % MOD;
			}

			out.println(ans);
		}

		private void addSegment(long[] inc, int l, int r, int val) {
			inc[l] += val;
			if (inc[l] >= MOD) {
				inc[l] -= MOD;
			}
			inc[r + 1] -= val;
			if (inc[r + 1] < 0) {
				inc[r + 1] += MOD;
			}
		}

		private void precalc() {
			inv[1] = 1;
			for (int i = 2; i < N; i++) {
				inv[i] = (int) ((MOD - (MOD / i) * (long) inv[MOD % i] % MOD) % MOD);
			}
			fact[0] = 1;
			invFact[0] = 1;
			for (int i = 1; i < N; i++) {
				fact[i] = (int) (i * (long) fact[i - 1] % MOD);
				invFact[i] = (int) (inv[i] * (long) invFact[i - 1] % MOD);
			}
		}

	}

	static class FastScanner {
		private BufferedReader in;
		private StringTokenizer st;

		public FastScanner(InputStream stream) {
			in = new BufferedReader(new InputStreamReader(stream));
		}

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

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

	}
}