import java.util.*;

// ABC 48-C
// http://abc048.contest.atcoder.jp/tasks/arc064_a

public class Main {

	static int MOD = 1000000007;

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

		int n = in.nextInt();
		long[] candies = new long[n];
		long x = in.nextLong();

		for (int i = 0; i < n; i++) {
			candies[i] = in.nextLong();
		}

		int answer = 0;
		for (int i = 1; i < n; i++) {
//			int sum = candies[i - 1] + candies[i];
//			if (sum > x) {
//				int diff = sum - x;
//				answer += diff;
//				if (diff <= candies[i]) {
//					candies[i] -= diff;
//				} else {
//					candies[i] = 0;
//				}
//			}
			long sum = candies[i - 1] + candies[i];
			long k = Math.max(0, sum - x);
			answer += k;
			candies[i] = Math.max(0, candies[i] - k);
		}

		System.out.println(answer);
	}
}

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

Find the minimum number of operations required to achieve the objective.

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

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

N x
a_1 a_2 ... a_N

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;

public class Main {
    InputStream is;

    int __t__ = 1;
    int __f__ = 0;
    int __FILE_DEBUG_FLAG__ = __f__;
    String __DEBUG_FILE_NAME__ = "src/D1";

    FastScanner in;
    PrintWriter out;

    int MOD = 1000000007;
    public void solve() {
        int N = in.nextInt();
        int[] a = in.nextIntArray(N);
        int[] cnt = new int[33];

        int xor = 0;
        for (int i = 0; i < N; i++) {
            int d = Integer.bitCount(a[i] ^ (a[i] - 1));
            cnt[d]++;
            xor ^= a[i];
        }

        int res = 0;
        for (int i = cnt.length - 1; i >= 0; i--) {
            if (cnt[i] == 0) {
                if ((xor & (1L << (i - 1))) == 0) {
                    continue;
                } else {
                    System.out.println(-1);
                    return;
                }
            }
            xor ^= (1L << i) - 1;
            res++;
        }
        System.out.println(res);
    }

    long MULT(long x, long y) {
        return (x * y) % MOD;
    }

    long POW(long a, long p) {
        long res = 1;
        long val = a;
        while (p > 0) {
            if (p % 2 == 1) {
                res = MULT(res, val);
            }
            p >>= 1;
            val = MULT(val, val);
        }
        return res;
    }

    public void run() {
        if (__FILE_DEBUG_FLAG__ == __t__) {
            try {
                is = new FileInputStream(__DEBUG_FILE_NAME__);
            } catch (FileNotFoundException e) {
                // TODO 自動生成された catch ブロック
                e.printStackTrace();
            }
            System.out.println("FILE_INPUT!");
        } else {
            is = System.in;
        }
        in = new FastScanner(is);
        out = new PrintWriter(System.out);

        solve();
    }

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

    class FastScanner {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastScanner(InputStream stream) {
            this.stream = stream;
            // stream = new FileInputStream(new File("dec.in"));

        }

        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++];
        }

        boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        boolean isEndline(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

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

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

            return array;
        }

        int[][] nextIntMap(int n, int m) {
            int[][] map = new int[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextIntArray(m);
            }
            return map;
        }

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

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

            return array;
        }

        long[][] nextLongMap(int n, int m) {
            long[][] map = new long[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextLongArray(m);
            }
            return map;
        }

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

        double[] nextDoubleArray(int n) {
            double[] array = new double[n];
            for (int i = 0; i < n; i++)
                array[i] = nextDouble();

            return array;
        }

        double[][] nextDoubleMap(int n, int m) {
            double[][] map = new double[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextDoubleArray(m);
            }
            return map;
        }

        String next() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        String[] nextStringArray(int n) {
            String[] array = new String[n];
            for (int i = 0; i < n; i++)
                array[i] = next();

            return array;
        }

        String nextLine() {
            int c = read();
            while (isEndline(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndline(c));
            return res.toString();
        }
    }
}

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

Score : 500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

A cheetah and a cheater are going to play the game of Nim.
In this game they use N piles of stones.
Initially the i-th pile contains a_i stones.
The players take turns alternately, and the cheetah plays first.
In each turn, the player chooses one of the piles, and takes one or more stones from the pile.
The player who can't make a move loses.

However, before the game starts, the cheater wants to cheat a bit to make sure that he can win regardless of the moves by the cheetah.
From each pile, the cheater takes zero or one stone and eats it before the game.
In case there are multiple ways to guarantee his winning, he wants to minimize the number of stones he eats.

Compute the number of stones the cheater will eat.
In case there is no way for the cheater to win the game even with the cheating, print -1 instead.

Constraints

1 ≤ N ≤ 10^5

2 ≤ a_i ≤ 10^9

Input

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

N
a_1
:
a_N

Output

Print the answer.

Sample Input 1

3
2
3
4

Sample Output 1

3

The only way for the cheater to win the game is to take stones from all piles and eat them.

Sample Input 2

3
100
100
100

Sample Output 2

-1

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.*;
import java.util.*;
import java.util.function.IntPredicate;

public class Main {
	class Pair{
		int idx;
		int value;
		public Pair(int idx, int value){
			this.idx = idx;
			this.value = value;
		}
	}

	int N, M, K;
	Pair[] A;
	public void solve() {
		N = nextInt();
		M = nextInt();
		K = nextInt();
		A = new Pair[N];
		for(int i = 0; i < N; i++){
			A[i] = new Pair(i, nextInt());
		}
		Arrays.sort(A, (a, b) -> Integer.compare(b.value, a.value));
		long ans = 0;
		for(int i = 0; i < K; i++){
			ans += A[i].value;
		}
		out.println(ans);

	}

	private static PrintWriter out;

	public static void main(String[] args) {
		out = new PrintWriter(System.out);
		new Main().solve();
		out.flush();
	}

	public static int nextInt() {
		int num = 0;
		String str = next();
		boolean minus = false;
		int i = 0;
		if (str.charAt(0) == '-') {
			minus = true;
			i++;
		}
		int len = str.length();
		for (; i < len; i++) {
			char c = str.charAt(i);
			if (!('0' <= c && c <= '9'))
				throw new RuntimeException();
			num = num * 10 + (c - '0');
		}
		return minus ? -num : num;
	}

	public static long nextLong() {
		long num = 0;
		String str = next();
		boolean minus = false;
		int i = 0;
		if (str.charAt(0) == '-') {
			minus = true;
			i++;
		}
		int len = str.length();
		for (; i < len; i++) {
			char c = str.charAt(i);
			if (!('0' <= c && c <= '9'))
				throw new RuntimeException();
			num = num * 10l + (c - '0');
		}
		return minus ? -num : num;
	}

	public static String next() {
		int c;
		while (!isAlNum(c = read())) {
		}
		StringBuilder build = new StringBuilder();
		build.append((char) c);
		while (isAlNum(c = read())) {
			build.append((char) c);
		}
		return build.toString();
	}

	private static byte[] inputBuffer = new byte[1024];
	private static int bufferLength = 0;
	private static int bufferIndex = 0;

	private static int read() {
		if (bufferLength < 0)
			throw new RuntimeException();
		if (bufferIndex >= bufferLength) {
			try {
				bufferLength = System.in.read(inputBuffer);
				bufferIndex = 0;
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			if (bufferLength <= 0)
				return (bufferLength = -1);
		}
		return inputBuffer[bufferIndex++];
	}

	private static boolean isAlNum(int c) {
		return '!' <= c && c <= '~';
	}
}

Score : 700 points

Problem Statement

There are N panels arranged in a row in Takahashi's house, numbered 1 through N. The i-th panel has a number A_i written on it. Takahashi is playing by throwing balls at these panels.

Takahashi threw a ball K times. Let the panel hit by a boll in the i-th throw be panel p_i. He set the score for the i-th throw as i \times A_{p_i}.

He was about to calculate the total score for his throws, when he realized that he forgot the panels hit by balls, p_1,p_2,...,p_K. The only fact he remembers is that for every i (1 ≦ i ≦ K-1), 1 ≦ p_{i+1}-p_i ≦ M holds. Based on this fact, find the maximum possible total score for his throws.

Constraints

1 ≦ M ≦ N ≦ 100,000

1 ≦ K ≦ min(300,N)

1 ≦ A_i ≦ 10^{9}

Partial Scores

In the test set worth 100 points, M = N.

In the test set worth another 200 points, N ≦ 300 and K ≦ 30.

In the test set worth another 300 points, K ≦ 30.

Input

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

N M K
A_1 A_2 … A_N

Output

Print the maximum possible total score for Takahashi's throws.

Sample Input 1

5 2 3
10 2 8 10 2

Sample Output 1

56

The total score is maximized when panels 1,3 and 4 are hit, in this order.

Sample Input 2

5 5 2
5 2 10 5 9

Sample Output 2

28

This case satisfies the additional constraint M = N for a partial score.

Sample Input 3

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

Sample Output 3

5000000078


import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int Q = sc.nextInt();
		int[] A = new int[Q];
		int[] B = new int[Q];
		long[] C = new long[Q];
		long[] min_cost = new long[N];
		Arrays.fill(min_cost, Long.MAX_VALUE/ 10);
		PriorityQueue<Edge> pq = new PriorityQueue<>();
		for (int i = 0; i < Q; ++i) {
			A[i] = sc.nextInt();
			B[i] = sc.nextInt();
			C[i] = sc.nextInt();
			pq.add(new Edge(A[i], B[i], C[i]));
			min_cost[A[i]] = Math.min(min_cost[A[i]], C[i] + 1);
			min_cost[B[i]] = Math.min(min_cost[B[i]], C[i] + 2);
		}
		for (int i = 0; i < 2 * N; ++i) {
			min_cost[(i + 1) % N] = Math.min(min_cost[(i + 1) % N], min_cost[i % N] + 2);
		}
		for (int i = 0; i < N; ++i) {
			pq.add(new Edge(i, (i + 1) % N, min_cost[i]));
		}
		DJSet ds = new DJSet(N);
		long ret = 0;
		while (!pq.isEmpty()) {
			Edge edge = pq.poll();
			if (ds.equiv(edge.a, edge.b))
				continue;
			ret += edge.cost;
			ds.setUnion(edge.a, edge.b);
			pq.add(new Edge(edge.b, (edge.a + 1) % N, edge.cost + 1));
		}
		System.out.println(ret);

	}

	static class DJSet {
		int n = 1;
		int[] upper;

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

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

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

		void setUnion(int x, int y) {
			x = root(x);
			y = root(y);
			if (x != y) {
				if (upper[x] < upper[y]) {
					int d = x;
					x = y;
					y = d;
				}
				upper[y] += upper[x];
				upper[x] = y;
			}
		}
	}

	static class Edge implements Comparable<Edge> {
		int a;
		int b;
		long cost;

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

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

Score : 1300 points

Problem Statement

We have a graph with N vertices, numbered 0 through N-1. Edges are yet to be added.

We will process Q queries to add edges.
In the i-th (1≦i≦Q) query, three integers A_i, B_i and C_i will be given, and we will add infinitely many edges to the graph as follows:

The two vertices numbered A_i and B_i will be connected by an edge with a weight of C_i.

The two vertices numbered B_i and A_i+1 will be connected by an edge with a weight of C_i+1.

The two vertices numbered A_i+1 and B_i+1 will be connected by an edge with a weight of C_i+2.

The two vertices numbered B_i+1 and A_i+2 will be connected by an edge with a weight of C_i+3.

The two vertices numbered A_i+2 and B_i+2 will be connected by an edge with a weight of C_i+4.

The two vertices numbered B_i+2 and A_i+3 will be connected by an edge with a weight of C_i+5.

The two vertices numbered A_i+3 and B_i+3 will be connected by an edge with a weight of C_i+6.

...

Here, consider the indices of the vertices modulo N.
For example, the vertice numbered N is the one numbered 0, and the vertice numbered 2N-1 is the one numbered N-1.

The figure below shows the first seven edges added when N=16, A_i=7, B_i=14, C_i=1:

After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph.

Constraints

2≦N≦200,000

1≦Q≦200,000

0≦A_i,B_i≦N-1

1≦C_i≦10^9

Input

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

N Q
A_1 B_1 C_1
A_2 B_2 C_2
:
A_Q B_Q C_Q

Output

Print the total weight of the edges contained in a minimum spanning tree of the graph.

Sample Input 1

7 1
5 2 1

Sample Output 1

21

The figure below shows the minimum spanning tree of the graph:

Note that there can be multiple edges connecting the same pair of vertices.

Sample Input 2

2 1
0 0 1000000000

Sample Output 2

1000000001

Also note that there can be self-loops.

Sample Input 3

5 3
0 1 10
0 2 10
0 4 10

Sample Output 3

42


import java.util.Scanner;
import java.util.stream.IntStream;

public class Main{
	static final Scanner s=new Scanner(System.in);
	static int getInt(){
		return Integer.parseInt(s.next());
	}
	public static void main(String[] __){
		int h=getInt(),w=getInt();
		for(int i=1;i<=h;i++)
			for(char c='A';c-'A'<w;c++)
				if(s.next().equals("snuke"))
					System.out.println(""+c+i);
	}
}

Score : 100 points

Problem Statement

There is a grid with H rows and W columns.

The square at the i-th row and j-th column contains a string S_{i,j} of length 5.

The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from A through the W-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the 6-th row and 8-th column should be reported as H6.

Constraints

1≦H, W≦26

The length of S_{i,j} is 5.

S_{i,j} consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

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

H W
S_{1,1} S_{1,2} ... S_{1,W}
S_{2,1} S_{2,2} ... S_{2,W}
:
S_{H,1} S_{H,2} ... S_{H,W}

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


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

public class Main {

    public static void main(String[] args){
        new Main().solve();
    }
    int n,m;
    int[]k;
    int[][]l;
    boolean[][]edge;
    boolean[] visited;
    void solve() {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        k = new int[n];
        l = new int[n][];

        for (int i = 0; i < n; i++) {
            k[i] = Integer.parseInt(sc.next());
            l[i] = new int[k[i]];
            for (int j = 0; j < k[i]; j++) {
                l[i][j] = Integer.parseInt(sc.next());
            }
        }
        edge = new boolean[n+m][n+m];
        for(int i=0;i<n;i++) {
            for (int j = 0; j < k[i]; j++) {
                edge[i][(n - 1) + l[i][j]] = true;
                edge[(n - 1) + l[i][j]][i] = true;
            }
        }

        visited=new boolean[n+m];
        dfs(0);
        for(int i=0;i<n;i++){
            if(!visited[i]){
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }

    void dfs(int x) {
        visited[x] = true;
        for (int i = 0; i < n+m; i++) {
            if (!visited[i] && edge[x][i]) {
                dfs(i);
            }
        }
    }
}

Score : 400 points

Problem Statement

On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M.

For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet.

The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}.

Two participants A and B can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both A and B can speak.

There exists a participant X that both A and B can communicate with.

Determine whether all N participants can communicate with all other participants.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦K_i≦M

(The sum of all K_i)≦10^5

1≦L_{i,j}≦M

L_{i,1}, L_{i,2}, ..., L_{i,{}K_i} are pairwise distinct.

Partial Score

200 points will be awarded for passing the test set satisfying the following: N≦1000, M≦1000 and (The sum of all K_i)≦1000.

Additional 200 points will be awarded for passing the test set without additional constraints.

Input

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

N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N}

Output

If all N participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants 1 and 2: both can speak language 2.

Participants 2 and 3: both can speak language 4.

Participants 1 and 3: both can communicate with participant 2.

Participants 3 and 4: both can speak language 6.

Participants 2 and 4: both can communicate with participant 3.

Participants 1 and 4: both can communicate with participant 2.

Note that there can be languages spoken by no participant.

Sample Input 2

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

Sample Output 2

NO

For example, participants 1 and 3 cannot communicate with each other.


import java.util.Scanner;

	public class Main {

		public static void main(String[] args) {

			Scanner sc = new Scanner(System.in);

			int h = sc.nextInt();
			int w = sc.nextInt();

			char[][] ac = new char[h][w];
			String S;

			for(int i=0;i<h;i++) {
				S = sc.next();
				for(int j=0;j<w;j++) {
					ac[i][j] = S.charAt(j);
				}
			}

			int num = 0;

			for(int i=0;i<h;i++) {
				for(int j=0;j<w;j++) {
					if(ac[i][j]=='#') {
						num++;
					}
				}
			}

			if(num != h+w-1) {
				System.out.println("Impossible");
				return;
			}

			int x = 0;
			int y = 0;

			for(int j=1;j<num;j++) {
				if((ac[x][y+1]!='#')&&(ac[x+1][y]!='#')) {
					System.out.println("Impossible");
					return;
				}

				if(y<=w-1) {
					if((ac[x][y+1]=='#')) {
						y++;
					}
				}

				if(x<=h-1) {
					if((ac[x+1][y]=='#')) {
						x++;
					}
				}

			}

			System.out.println("Possible");

		}

	}

Score : 200 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is # if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints

2 \leq H, W \leq 8

a_{i,j} is either # or ..

There exists a valid sequence of moves for Shik to generate the map a.

Input

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

H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}

Output

If it is possible that Shik only uses right and down moves, print Possible. Otherwise, print Impossible.

Sample Input 1

4 5
##...
.##..
..##.
...##

Sample Output 1

Possible

The matrix can be generated by a 7-move sequence: right, down, right, down, right, down, and right.

Sample Input 2

5 3
###
..#
###
#..
###

Sample Output 2

Impossible

Sample Input 3

4 5
##...
.###.
.###.
...##

Sample Output 3

Impossible


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.PriorityQueue;

public class Main {
	private static final int UNDEFINED = -1000000;

	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/D1";

	FastScanner in;
	PrintWriter out;

	public void solve() {
		int n = in.nextInt(), m = in.nextInt();
		char[][] s = new char[n][];
		for (int i = 0; i < n; i++) {
			s[i] = in.next().toCharArray();
		}
		if (s[0][0] == '#' || s[n-1][m-1] == '#') {
			System.out.println("Impossible");
			return;
		}
		int cx = 0, cy = 0;
		while (cx != m - 1 || cy != n - 1) {
			boolean f1 = false, f2 = false;
			if (cx < m - 1 && s[cy][cx+1] == '#')
				f1 = true;
			if (cy < n - 1 && s[cy+1][cx] == '#')
				f2 = true;

			if ((f1 ^ f2) == false) {
				System.out.println("Impossible");
				return;
			} else if (f1) {
				cx++;
			} else {
				cy++;
			}
		}
		System.out.println("Possible");
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		Thread t = new Thread(null, new Runnable() {

			@Override
			public void run() {
				solve();
			}
		}, "lul", 1 << 30);
		t.start();
	}

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

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		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++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

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

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

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

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

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

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

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

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}


import java.util.*;

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

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

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

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

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


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

		Arrays.sort(X);

		if(X[0] + X[1] == X[2]){
			System.out.println("Yes");
		}else{
			System.out.println("No");
		}
	}
}


import java.util.Scanner;

/**
 * https://abc047.contest.atcoder.jp/tasks/arc063_b
 */
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		long T = sc.nextLong();
		long[] a = new long[N];
		for(int i=0; i<N; i++) a[i] = sc.nextLong();
		sc.close();
		long[] maxDp = new long[N];
		maxDp[N-1] = a[N-1];
		for(int i=N-2; i>=0; i--){
			maxDp[i] = Math.max(a[i], maxDp[i+1]);
		}

		long max = Long.MIN_VALUE;
		int count = 0;
		for(int i=0; i<N-1; i++){
			long s = maxDp[i+1]-a[i];
			if(s==max){
				count++;
			}else if(s>max){
				max = s;
				count = 1;
			}
		}
		//long ans = max<=0 ? 0 : Math.min(count, T/2);
		System.out.println(count);

	}

}

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

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

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2


import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		String str=scan.next();
		char a=str.charAt(0);
		int count=0;
		for(int i=1;i!=str.length();i++) {
			char b=str.charAt(i);
			if(a!=b) {
				count++;
			}
			a=str.charAt(i);
		}
		System.out.println(count);
	}
}

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

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

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


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

/**
 * Created by fcdkbear on 15.10.16.
 */
public class Main {

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

    static class Task {

        public void solve(InputReader in, PrintWriter out) {

            String s = in.next();
            int cIndex = s.indexOf('C');
            int fIndex = s.lastIndexOf('F');
            if ((cIndex == -1) || (fIndex == -1) || (cIndex > fIndex)) {
                out.println("No");
            } else {
                out.println("Yes");
            }

        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

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

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

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

    }

}

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

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

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


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

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 Scanner in = new Scanner(System.in);
	     int k = in.nextInt();
	     int t = in.nextInt();

	     int arr[] = new int[t];
	     for(int i=0;i<t;i++)
	    	 arr[i]=in.nextInt();

	     Arrays.sort(arr);
	     int step =0;
	     int ans=0;
	     while(step<k){
	    	 int get = 0;
	    	 for(int i=arr.length-1;i>=0;i--){
	    		 if(arr[i]>0){
	    			 get++;
	    			 arr[i]--;
	    		 }
	    		 if(get==2)
	    			 break;
	    	 }
	    	 step+=get;
	    	 if(get==1 && step!=k)
	    		 ans++;
	     }
    		 System.out.println(ans);

	}

}

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

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

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


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

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);
		TaskX solver = new TaskX();
		solver.solve(1, in, out);
		out.close();
	}

	static int INF = 1 << 30;
	static long LINF = 1L << 55;
	static int MOD = 1000000007;
	static int[] mh4 = { 0, -1, 1, 0 };
	static int[] mw4 = { -1, 0, 0, 1 };
	static int[] mh8 = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] mw8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static class TaskX {

		public void solve(int testNumber, MyInput in, PrintWriter out) {

			int n = in.nextInt();
			long[] t = in.nextLongArray(n);
			long[] a = in.nextLongArray(n);

			long[] tc = new long[n], ac = new long[n];
			long min = -1;

			long tmax = Arrays.stream(t).max().getAsLong();
			long amax = Arrays.stream(a).max().getAsLong();

			if (tmax != amax) {
				out.println(0);
				return;
			}

			for (int i = 0; i < n; i++) {
				if (t[i] > min) {
					min = t[i];
					tc[i] = 1;
					continue;
				}
				tc[i] = t[i];
			}

			min = -1;
			for (int i = n-1; i >= 0; i--) {
				if (a[i] > min) {
					min = a[i];
					ac[i] = 1;
					continue;
				}
				ac[i] = a[i];
			}

			long[] cnt = new long[n];
			for (int i = 0; i < n; i++) {
				cnt[i] = Math.min(ac[i], tc[i]);
			}

			long ans = 1;
			for (long l : cnt) {
				ans *= l;
				ans %= MOD;
			}
			out.println(ans);
		}
	}

	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 = 0;
			if (str[0] == '-') {
				i = 1;
			}
			for (; i < len; i++)
				ret = ret * 10 + str[i] - '0';
			if (str[0] == '-') {
				ret = -ret;
			}
			return ret;
		}

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

		public String nextString() {
			return new String(nextChars());
		}

		public char[] nextChars() {
			int len = 0;
			str[len++] = nextChar();
			len = reads(len, isSpace);
			return Arrays.copyOf(str, len);
		}

		public char[][] next2DChars(int h, int w) {
			char[][] s = new char[h][w];
			for (int i = 0; i < h; i++) {
				s[i] = nextChars();
			}
			return s;
		}

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

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

		public int[] nextIntArray1Index(final int n) {
			final int[] res = new int[n + 1];
			for (int i = 1; i < n + 1; i++) {
				res[i] = nextInt();
			}
			return res;
		}

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

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

		public long[] nextLongArray1Index(final int n) {
			final long[] res = new long[n + 1];
			for (int i = 1; i < n + 1; i++) {
				res[i] = nextLong();
			}
			return res;
		}

		public long[] nextLongArrayDec(final int n) {
			final long[] res = new long[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextLong() - 1;
			}
			return res;
		}

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

		public double[] nextDoubleArray(int n) {
			double[] res = new double[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextDouble();
			}
			return res;
		}

		static class EndOfFileRuntimeException extends RuntimeException {
		}

	}

}

Score : 400 points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.

The height of Mt. i is h_i, but they have forgotten the value of each h_i.
Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i.

We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0.

Constraints

1 ≤ N ≤ 10^5

1 ≤ T_i ≤ 10^9

1 ≤ A_i ≤ 10^9

T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1)

A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1)

Input

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

N
T_1 T_2 ... T_N
A_1 A_2 ... A_N

Output

Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

1, 3, 2, 2, 2

1, 3, 2, 1, 2

1, 3, 1, 2, 2

1, 3, 1, 1, 2

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo 10^9 + 7.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.


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);
		ProblemD solver = new ProblemD();
		solver.solve(1, in, out);
		out.close();
	}

	static class ProblemD {
		public void solve(int testNumber, FastScanner in, PrintWriter out) {
			int height = in.nextInt();
			int width = in.nextInt();
			char[][] s = new char[height][];
			for (int r = 0; r < height; r++) {
				s[r] = in.next().toCharArray();
			}
			final int infinity = 1000000000;
			int n = height;
			int[][] c1 = new int[n + 1][n + 1];
			int[][] c2 = new int[n + 1][n + 1];
			for (int s1 = 0; s1 <= n; s1++) {
				for (int s2 = 0; s2 <= n; s2++) {
					for (int r = 0; r < height; r++) {
						if (r >= s1 && r >= s2 && s[r - s1][0] == s[r - s2][1]) {
							++c1[s1][s2];
						}
						if (width == 3 && r >= s1 && r >= s2 && s[r - s1][1] == s[r - s2][2]) {
							++c2[s1][s2];
						}
					}
				}
			}
			int[][][] d = new int[n + 1][n + 1][n + 1];
			for (int s1 = n; s1 >= 0; s1--) {
				for (int s2 = n; s2 >= 0; s2--) {
					for (int s3 = n; s3 >= 0; s3--) {
						if (s1 == n && s2 == n && s3 == n) {
							d[s1][s2][s3] = 0;
						} else {
							d[s1][s2][s3] = infinity;
						}
						if (s1 < n) {
							d[s1][s2][s3] = Math.min(d[s1][s2][s3], d[s1 + 1][s2][s3] + c1[s1][s2]);
						}
						if (s2 < n) {
							d[s1][s2][s3] = Math.min(d[s1][s2][s3], d[s1][s2 + 1][s3] + c1[s1][s2] + c2[s2][s3]);
						}
						if (s3 < n) {
							d[s1][s2][s3] = Math.min(d[s1][s2][s3], d[s1][s2][s3 + 1] + c2[s2][s3]);
						}
					}
				}
			}
			if (width == 2) {
				out.println(d[0][0][n]);
			} else {
				out.println(d[0][0][0]);
			}
		}

	}

	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 {
					st = new StringTokenizer(in.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return st.nextToken();
		}

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

	}
}

Score : 800 points

Problem Statement

Mr. Takahashi has in his room an art object with H rows and W columns, made up of H \times W blocks.
Each block has a color represented by a lowercase English letter (a-z).
The color of the block at the i-th row and j-th column is c_{i,j}.

Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for his tastes.
The dismantling is processed by repeating the following operation:

Choose one of the W columns and push down that column one row.
The block at the bottom of that column disappears.

Each time the operation is performed, a cost is incurred.
Since blocks of the same color have a property to draw each other together, the cost of the operation is the number of the pairs of blocks (p, q) such that:

The block p is in the selected column.

The two blocks p and q are horizontally adjacent (before pushing down the column).

The two blocks p and q have the same color.

Mr. Takahashi dismantles the object by repeating the operation H \times W times to get rid of all the blocks.
Compute the minimum total cost to dismantle the object.

Constraints

1 ≤ H ≤ 300

2 ≤ W ≤ 300

All characters c_{i,j} are lowercase English letters (a-z).

Partial Score

In test cases worth 300 points, W = 3.

Input

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

H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W}

Output

Print the minimum total cost to dismantle the object.

Sample Input 1

2 3
rrr
brg

Sample Output 1

2

For example, the total cost of 2 can be achieved by performing the operation as follows and this is the minimum value.

Sample Input 2

6 3
xya
xya
ayz
ayz
xaz
xaz

Sample Output 2

0

The total cost of 0 can be achieved by first pushing down all blocks of the middle column, then all of the left column, and all of the right column.

Sample Input 3

4 2
ay
xa
xy
ay

Sample Output 3

0

The total cost of 0 can be achieved by the following operations:

pushing down the right column one row;

pushing down the left column one row;

pushing down all of the right column;

and pushing down all of the left column.

Sample Input 4

5 5
aaaaa
abbba
ababa
abbba
aaaaa

Sample Output 4

24

Sample Input 5

7 10
xxxxxxxxxx
ccccxxffff
cxxcxxfxxx
cxxxxxffff
cxxcxxfxxx
ccccxxfxxx
xxxxxxxxxx

Sample Output 5

130


import java.util.*;

public class Main{
	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		int a =in.nextInt(), b = in.nextInt(), c = in.nextInt();
		int count = 0;
		if(a!=b) {
			count++;
		}
		if(b!=c) {
			count++;
		}
		if(a!=c) {
			count++;
		}
		if(count == 3) {
			System.out.println("3");
			System.out.print("Three different colors: "+a+", "+b+" and "+c+".");
		}
		if(count == 2) {
			if(a==c) c = b;
			System.out.println("2");
			System.out.print("Two different colors: "+a+" and "+c+".");
		}
		if(count == 0) {
			System.out.println("1");
			System.out.print("One different color: "+a+".");
		}
		in.close();
	}
}

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


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

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

		// 入力
		int n = sc.nextInt();

		// 計算
		long result = 0;
		long t = 0;
		long a = 0;
		for(int i = 0; i < n; i++){
		    long nt = sc.nextLong();
		    long na = sc.nextLong();
		    long tempt = nt;
		    long tempa = na;
		    int cnt = 2;
		    while(t > tempt || a > tempa){
		        tempt = nt*cnt;
		        tempa = na*cnt;
		        cnt++;
		    }
		    t = tempt;
		    a = tempa;
		}
		result = t + a;

		// 出力
		System.out.println(result);
	}

	public static class Scanner {
		private BufferedReader br; private StringTokenizer tok;
		public Scanner(InputStream is) throws IOException { br = new BufferedReader(new InputStreamReader(is));}
		private void getLine() throws IOException { while(!hasNext()) tok = new StringTokenizer(br.readLine());}
		private boolean hasNext() { return tok != null && tok.hasMoreTokens();}
		public String next() throws IOException { getLine(); return tok.nextToken();}
		public int nextInt() throws IOException { return Integer.parseInt(next());}
		public long nextLong() throws IOException { return Long.parseLong(next());}
		public double nextDouble() throws IOException { return Double.parseDouble(next());}
	}
}

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

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

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


import java.util.*;
public class Main{
	public static void main(String[] args){
		Scanner sn = new Scanner(System.in);
		int N = sn.nextInt();
		long A = 1L,B = 1L;
		for(int i = 0; i < N; ++i){
			long x = sn.nextLong();
			long y = sn.nextLong();
			double A_x = (double)A/(double)x;
			double B_y = (double)B/(double)y;
			long n = (long)Math.max(Math.ceil(A_x),Math.ceil(B_y));
			A = n*x;
			B = n*y;
		}
		System.out.println(A+B);
	}
}


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

public class Main {

	static String collectStr = "CODEFESTIVAL2016";

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine();
		int cnt = 0;
		for (int i=0; i<line.length(); i++) {
			if (collectStr.charAt(i) != line.charAt(i)) {
				cnt++;
			}
		}
		System.out.println(cnt);
		long end = System.currentTimeMillis();
		//System.out.println((end-start) + "ms");
	}

}

Score : 100 points

Problem Statement

CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.

He intended to write CODEFESTIVAL2016 on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length.

So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to CODEFESTIVAL2016.

Find the minimum number of iterations for the rewrite operation.

Constraints

S is 16 characters long.

S consists of uppercase and lowercase alphabet letters and numerals.

Input

Inputs are provided from Standard Input in the following form.

S

Output

Output an integer representing the minimum number of iterations needed for the rewrite operation.

Sample Input 1

C0DEFESTIVAL2O16

Sample Output 1

2

The second character 0 must be changed to O and the 14th character O changed to 0.

Sample Input 2

FESTIVAL2016CODE

Sample Output 2

16


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 K = sc.nextInt();
		char[] P = new char[N];

//		int tmp = N/K;

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

			String tmp  = sc.next();
			P[i] = tmp.charAt(0);
		}

		Arrays.sort(P);

		int count = 1;
		int open = 0;
		char a = ' ';

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

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

				if(P[j] == ' ') continue;

				if (j == 0) {
					a = P[j];
					count = 1;
				} else {
					if(a != P[j]) {
						a = P[j];
						count++;
						P[j] = ' ';
						if (count == K) {
							open += 1;
							count = 1;
							break;
						}
					}
				}
			}
		}

		System.out.println(open);

//		for (int i = 0; i < N ;i++){
//			System.out.println(P[i]);
//		}

		sc.close();
	}
}

Score : 100 points

Problem Statement

Kyoto University Programming Contest is a programming contest voluntarily held by some Kyoto University students.
This contest is abbreviated as Kyoto University Programming Contest and called KUPC.

source: Kyoto University Programming Contest Information

The problem-preparing committee met to hold this year's KUPC and N problems were proposed there.
The problems are numbered from 1 to N and the name of i-th problem is P_i.
However, since they proposed too many problems, they decided to divide them into some sets for several contests.

They decided to divide this year's KUPC into several KUPCs by dividing problems under the following conditions.

One KUPC provides K problems.

Each problem appears at most once among all the KUPCs.

All the first letters of the problem names in one KUPC must be different.

You, one of the committee members, want to hold as many KUPCs as possible.
Write a program to find the maximum number of KUPCs that can be held this year.

Constraints

1 \leq N \leq 10^4

1 \leq K \leq 26

1 \leq |P_i| \leq 10

All characters in P_i are capital letters.

Note that, for each i and j (1 \leq i < j \leq N),
P_i \neq P_j are not necessarily satisfied.

Input

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

N K
P_1
:
P_N

Output

Print the maximum number of KUPCs that can be held on one line.

Sample Input 1

9 3
APPLE
ANT
ATCODER
BLOCK
BULL
BOSS
CAT
DOG
EGG

For example, three KUPCs can be held by dividing the problems as follows.

First: APPLE, BLOCK, CAT

Second: ANT, BULL, DOG

Third: ATCODER, BOSS, EGG

Sample Output 1

3

Sample Input 2

3 2
KU
KYOUDAI
KYOTOUNIV

Sample Output 2

0

No KUPC can be held.


import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		String x = sc.next();
		int ss = 0;
		int ts = 0;
		for (int i = 0; i < x.length(); i++) {
			if (x.charAt(i) == 'S') {
				ss++;
			} else {
				if (ss == 0) {
					ts++;
				} else {
					ss--;
				}
			}
		}
		System.out.println(ss + ts);
	}
}

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

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

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


import java.util.Scanner;

public class Main {

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

	public static void main(String[] args) {
		int n = sc.nextInt();
		int[] a = new int[n + 1];
		for (int i = 1; i <= n; i++) {
			a[i] = sc.nextInt();
		}
		int ans = 0;
		for (int i = 1; i <= n; i++) {
			if (a[a[i]] == i) {
				ans++;
			}
		}
		System.out.println(ans / 2);
	}
}

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

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

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


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;i++) a[i] = sc.nextInt();
		sc.close();

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

}


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

class Main{
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input = br.readLine();
		StringBuilder temp = new StringBuilder("");
		int n = Integer.parseInt(br.readLine());
		for(int i =0;i<input.length();i++){
			if(i==input.length()-1){
				char tempe = (char) ((int)input.charAt(i)+n);
				while(tempe>122)
					tempe-=26;
				temp.append(tempe);
				continue;
			}
			if(input.charAt(i)!='a'&&(int)'{'-  (int )input.charAt(i)<=n ){
				temp.append('a');
				n -= ((int)'{'-  (int )input.charAt(i));
			}else{
				temp.append(input.charAt(i));
			}
		}
		System.out.println(temp.toString());
	}
}

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

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

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


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

public class Main{
    static final Reader sc = new Reader();
    static final PrintWriter out = new PrintWriter(System.out,false);

    public static void main(String[] args) throws Exception {
    	int R = sc.nextInt();
        int C = sc.nextInt();
        int n = sc.nextInt();
        int[] r = new int[n];
        int[] c = new int[n];
        int[] a = new int[n];
        int[][] jjudge = new int[R][C];
        for(int i=0;i<R;i++){
            Arrays.fill(jjudge[i],-1);
        }
        for(int i=0;i<n;i++){
            r[i] = sc.nextInt()-1;
            c[i] = sc.nextInt()-1;
            a[i] = sc.nextInt();
            jjudge[r[i]][c[i]] = a[i];
        }
        ArrayList<Two> l2 = new ArrayList<Two>();
        ArrayList<ArrayList<One>> l1 = new ArrayList<ArrayList<One>>();
        for(int i=0;i<R;i++){
            ArrayList<One> x = new ArrayList<One>();
            l1.add(x);
        }
        for(int i=0;i<n;i++){
            if(r[i]!=R-1){
                if(jjudge[r[i]+1][c[i]]!=-1){
                    Two t = new Two(r[i],c[i],a[i],r[i]+1,c[i],jjudge[r[i]+1][c[i]]);
                    l2.add(t);
                }
                else{
                    ArrayList<One> x = l1.get(r[i]);
                    One o = new One(r[i],c[i],a[i]);
                    x.add(o);
                }
            }
            else{
                ArrayList<One> x = l1.get(R-1);
                One o = new One(r[i],c[i],a[i]);
                x.add(o);
            }
        }
        Point[] ten = new Point[R];
        for(int i=0;i<R;i++){
            ten[i] = new Point(-1,-1);
        }
        boolean flag = true;
        for(int j=0;j<l2.size();j++){
            Two t = l2.get(j);
            //out.println(t.x+" "+t.y+" "+t.z+" "+t.xx+" "+t.yy+" "+t.zz);
            if(ten[t.x].x==-1){
                ArrayList<One> x = l1.get(t.x);
                for(int i=0;i<x.size();i++){
                    One o = x.get(i);
                    if((t.y%2==0 && o.y%2==0) || (t.y%2==1 && o.y%2==1)){
                        if(o.z-t.z+t.zz<0){
                            flag = false;
                        }
                    }
                    else{
                        if(o.z+t.zz-t.z<0){
                            flag = false;
                        }
                    }
                }
                x = l1.get(t.xx);
                for(int i=0;i<x.size();i++){
                    One o = x.get(i);
                    if((t.y%2==0 && o.y%2==0) || (t.y%2==1 && o.y%2==1)){
                        if(t.z-t.zz+o.z<0){
                            flag = false;
                        }
                    }
                    else{
                        if(o.z+t.z-t.zz<0){
                            flag = false;
                        }
                    }
                }
                Point p = new Point(t.y,t.z-t.zz);
                ten[t.x] = p;
            }
            else{
                if((ten[t.x].x%2==0 && t.y%2==0) || (ten[t.x].x%2==1 && t.y%2==1)){
                    if(ten[t.x].y!=t.z-t.zz){
                        flag = false;
                    }
                }
                else{
                    if(ten[t.x].y!=t.zz-t.z){
                        flag = false;
                    }
                }
            }
            if(!flag){
                break;
            }
        }
        if(flag){
            out.println("Yes");
        }
        else{
            out.println("No");
        }
        out.flush();
        sc.close();
        out.close();
    }

    static void trace(Object... o) { System.out.println(Arrays.deepToString(o));}
}

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

class Two{
    int x;
    int y;
    int z;
    int xx;
    int yy;
    int zz;
    Two(int x,int y,int z,int xx,int yy,int zz){
        this.x = x;
        this.y = y;
        this.z = z;
        this.xx = xx;
        this.yy = yy;
        this.zz = zz;
    }
}

class One{
    int x;
    int y;
    int z;
    One(int x,int y,int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

class Reader {

    private final InputStream in;
    private final byte[] buf = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    public Reader() { this(System.in);}
    public Reader(InputStream source) { this.in = source;}

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

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

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

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

    public boolean hasNext() {skip(); 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();
        boolean minus = false;
        long num = readByte();

        if(num == '-'){
            num = 0;
            minus = true;
        }else if (num < '0' || '9' < num){
            throw new NumberFormatException();
        }else{
            num -= '0';
        }

        while(true){
            int b = readByte();
            if('0' <= b && b <= '9')
                num = num * 10 + (b - '0');
            else if(b == -1 || !isPrintableChar(b))
                return minus ? -num : num;
            else
                throw new NoSuchElementException();
        }
    }

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

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

    public char nextChar() {
        if (!hasNext()) throw new NoSuchElementException();
        return (char)readByte();
    }

    public String nextLine() {
        while (hasNextByte() && (buf[ptr] == '\n' || buf[ptr] == '\r')) ptr++;
        if (!hasNextByte()) throw new NoSuchElementException();

        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (b != '\n' && b != '\r') {
            sb.appendCodePoint(b);
            b = readByte();
        }

        return sb.toString();
    }

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

    public char[] nextCharArray(int n) {
        char[] res = new char[n];
        for (int i=0; i<n; i++) res[i] = nextChar();
        return res;
    }

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

Score : 800 points

Problem Statement

There is a grid with R rows and C columns.
We call the cell in the r-th row and c-th column (r，c).

Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i，c_i) for each i (1≤i≤N).
After that he fell asleep.

Mr. Aoki found the grid and tries to surprise Mr. Takahashi by writing integers into all remaining cells.
The grid must meet the following conditions to really surprise Mr. Takahashi.

Condition 1: Each cell contains a non-negative integer.

Condition 2: For any 2×2 square formed by cells on the grid, the sum of the top left and bottom right integers must always equal to the sum of the top right and bottom left integers.

Determine whether it is possible to meet those conditions by properly writing integers into all remaining cells.

Constraints

2≤R，C≤10^5

1≤N≤10^5

1≤r_i≤R

1≤c_i≤C

(r_i，c_i) ≠ (r_j，c_j) (i≠j)

a_i is an integer.

0≤a_i≤10^9

Input

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

R C
N
r_1 c_1 a_1
r_2 c_2 a_2
:
r_N c_N a_N

Output

Print Yes if it is possible to meet the conditions by properly writing integers into all remaining cells.
Otherwise, print No.

Sample Input 1

2 2
3
1 1 0
1 2 10
2 1 20

Sample Output 1

Yes

You can write integers as follows.

Sample Input 2

2 3
5
1 1 0
1 2 10
1 3 20
2 1 30
2 3 40

Sample Output 2

No

There are two 2×2 squares on the grid, formed by the following cells:

Cells (1，1), (1，2), (2，1) and (2，2)

Cells (1，2), (1，3), (2，2) and (2，3)

You have to write 40 into the empty cell to meet the condition on the left square, but then it does not satisfy the condition on the right square.

Sample Input 3

2 2
3
1 1 20
1 2 10
2 1 0

Sample Output 3

No

You have to write -10 into the empty cell to meet condition 2, but then it does not satisfy condition 1.

Sample Input 4

3 3
4
1 1 0
1 3 10
3 1 10
3 3 20

Sample Output 4

Yes

You can write integers as follows.

Sample Input 5

2 2
4
1 1 0
1 2 10
2 1 30
2 2 20

Sample Output 5

No

All cells already contain a integer and condition 2 is not satisfied.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        Main m = new Main(sc);
        m.show(m.solve());
        sc.close();
    }

	//フィールド
    Scanner sc;
    String A;
    String B;
    String C;
    int countA = 0;
    int countB = 0;
    int countC = 0;
    char next = 'a';

    //入力
    Main(Scanner sc) {
        this.sc = sc;
        this.A = sc.next();
        this.B = sc.next();
        this.C = sc.next();
    }

    //解答処理
    private String solve() {
        String answer = null;

        while (true) {
        	if (next == 'a') {
        		countA++;
        		if (A.length() == countA) {
            		answer = "A";
            		break;
            	}
        		next = A.charAt(countA);
        	} else if (next == 'b') {
        		countB++;
        		if (B.length() == countB) {
            		answer = "B";
            		break;
            	}
        		next = B.charAt(countB);
        	} else if (next == 'c') {
        		countC++;
        		if (C.length() == countC) {
            		answer = "C";
            		break;
            	}
        		next = C.charAt(countC);
        	}
        }

        return answer;
    }

    //出力
    public void show(String answer) {
        System.out.println(answer);
    }

}

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

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

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


import java.util.Scanner;

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

       String str_A = scan.next();
       String str_B = scan.next();
       String str_C = scan.next();
       check_input(str_A);
       check_input(str_B);
       check_input(str_C);

       int pos_A = 0;
       int pos_B = 0;
       int pos_C = 0;

       char ch = str_A.charAt(pos_A);
       pos_A++;

       while (pos_A < str_A.length() ||
              pos_B < str_B.length() ||
              pos_C < str_C.length() ) {
           if (ch == 'a') {
              if ( pos_A == str_A.length() ) {
                 System.out.println('A');
                 break;
              } else {
                 ch = str_A.charAt(pos_A);
                 pos_A++;
              }
           } else if (ch == 'b') {
              if ( pos_B == str_B.length() ) {
                 System.out.println('B');
                 break;
              } else {
                 ch = str_B.charAt(pos_B);
                 pos_B++;
              }
           } else if (ch == 'c') {
              if ( pos_C == str_C.length() ) {
                 System.out.println('C');
                 break;
              } else {
                 ch = str_C.charAt(pos_C);
                 pos_C++;
              }
           } else {
              System.exit(-1);
           }
       }
   }
   public static void check_input(String str) {
       if ((str.length() < 2) || (str.length() > 100)) {
           System.exit(-1);
       }
   }
}


import java.util.Scanner;

class Main {
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		String s = scanner.nextLine();
		long length = s.length();
		scanner.close();
		long sum = 0;
		for(int i=0;i<length;i++){
			long left = (long) Math.ceil(Math.pow(2, i-1));
			for(int j=i+1;j<length+1;j++){
				sum += (long) left * Long.valueOf(s.substring(i, j))* Math.ceil(Math.pow(2, length - j - 1));
			}
		}
		System.out.println(sum);
	}
}

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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

public class Main {

    private static final int INF = (int) 1e+9 + 7;
    private static Map<Long, Integer> idMap = new HashMap<>();
    private static Queue<Edge> edges = new ArrayDeque<>();

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int m = sc.nextInt();
        if (m == 0) {
            System.out.println(-1);
            return;
        }
        for (int i = 0; i < m; i++) {
            int p = sc.nextInt();
            int q = sc.nextInt();
            int c = sc.nextInt();
            edges.add(new Edge(toId(p, c), toId(q, c), 0));
            edges.add(new Edge(toId(p, c), toId(p, 0), 0));
            edges.add(new Edge(toId(p, 0), toId(p, c), 1));
            edges.add(new Edge(toId(q, c), toId(q, 0), 0));
            edges.add(new Edge(toId(q, 0), toId(q, c), 1));
        }
        long ans = dijkstra(toId(1, 0), toId(n, 0));
        System.out.println(ans == INF ? -1 : ans);
    }

    private static int toId(int fst, int snd) {
        long lid = ((long) (fst) << 32) + (long) (snd);
        Integer id = idMap.get(lid);
        if (id == null) {
            idMap.put(lid, id = idMap.size());
        }
        return id;
    }

    private static long dijkstra(int s, int t) {
        // O(E*logV)
        int[] d = new int[idMap.size()];
        Arrays.fill(d, INF);
        d[s] = 0;
        GraphL g = new GraphL(edges);
        PriorityQueue<PriorityPair> q = new PriorityQueue<>(PriorityPair::compareTo);
        q.add(new PriorityPair(s, 0));
        while (!q.isEmpty()) {
            PriorityPair pair = q.poll();
            int from = pair.element;
            if (d[from] < pair.priority) continue;
            g.getNext(from).stream().filter(to -> d[to] > d[from] + g.getWeight(from, to)).forEach(to -> {
                d[to] = d[from] + g.getWeight(from, to);
                q.add(new PriorityPair(to, d[to]));
            });
        }
        return d[t];
    }

}

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

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

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

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

    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());
    }
}
class PriorityPair implements Comparable<PriorityPair> {

    public int element;
    public int priority;

    public PriorityPair(int element, int priority) {
        this.element = element;
        this.priority = priority;
    }

    public PriorityPair(List<Integer> list) {
        this.element = list.get(0);
        this.priority = list.get(1);
    }

    public PriorityPair(int[] array) {
        this.element = array[0];
        this.priority = array[1];
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PriorityPair that = (PriorityPair) o;

        return element == that.element && priority == that.priority;

    }

    @Override
    public int hashCode() {
        int result = element;
        result = 31 * result + priority;
        return result;
    }

    @Override
    public int compareTo(PriorityPair o) {
        return Integer.compare(priority, o.priority);
    }

    @Override
    public String toString() {
        return "(" + element + ", priority=" + priority + ")";
    }
}

class Edge {

    int s;
    int t;
    int w;

    Edge(int s, int t, int w) {
        this.s = s;
        this.t = t;
        this.w = w;
    }
}

class GraphL {

    private Map<Integer, Set<Integer>> assoc;
    private Map<Long, Integer> weight;

    public GraphL(Queue<Edge> edges) {
        assoc = new HashMap<>();
        weight = new HashMap<>();
        for (Edge edge : edges) {
            assoc.putIfAbsent(edge.s, new HashSet<Integer>());
            assoc.get(edge.s).add(edge.t);
            weight.put(intPairToLong(edge.s, edge.t), edge.w);
        }
    }

    public boolean hasNext(int s) {
        return assoc.containsKey(s);
    }

    public boolean hasWeight(int s, int t) {
        return weight.containsKey(intPairToLong(s, t));
    }

    public Set<Integer> getNext(int s) {
        return assoc.get(s);
    }

    public int getWeight(int s, int t) {
        return weight.get(intPairToLong(s, t));
    }

    private static long intPairToLong(int fst, int snd) {
        return ((long) (fst) << 32) | (long) snd & 0xffffffffL;
    }

    private static int getFstFromLong(long intPair) {
        return (int) (intPair >> 32);
    }

    private static int getSndFromLong(long intPair) {
        return (int) (intPair & 0xffffffffL);
    }
}

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

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

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


import java.util.*;

public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int k = sc.nextInt();
    int x = sc.nextInt();
    int y = sc.nextInt();
    if(n<k){
      System.out.println(n*x);
      return;
    }
    System.out.println(k*x+(n-k)*y);
  }
}

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


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

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        main.solve();
    }
    private int ceil(int x, int y) {
        if (x % y == 0) {
            return x / y;
        }
        return x / y + 1;
    }
    public void solve() {
        Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int N = scan.nextInt();
        int A = scan.nextInt();
        int[] x = new int[N];
        int sum = 0;
        for (int i = 0; i < N; i++) {
            x[i] = scan.nextInt();
            sum += x[i];
        }
        int limit = ceil(sum, A) * A + 1;
        long[][][] dp = new long[N+1][N+1][limit];
        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= N; j++) {
                Arrays.fill(dp[i][j], 0);
            }
        }
        dp[0][0][0] = 1;
        for (int i = 1; i <= N; i++) {
            for (int j = 0; j <= N; j++) {
                for (int k = 0; k < limit; k++) {
                    // i枚目まででj枚を選択いて合計がk
                    if (x[i-1] <= k && 1 <= j) {
                        dp[i][j][k] = dp[i - 1][j][k] + dp[i - 1][j - 1][k - x[i - 1]];
                    } else {
                        dp[i][j][k] = dp[i-1][j][k];
                    }
                }
            }
        }
        long answer = 0;
        for (int j = 1; j <= N; j++) {
            answer += dp[N][j][j*A];
        }
        System.out.println(answer);
    }
}

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

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