import java.io.*;
import java.util.*;
public class Main {
  public static int array[];
  public static int minId;
  public static int minVal;
  public static void main(String[] args) throws Exception {
    String line = null;
    int res = 0;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    line = br.readLine();
    line = br.readLine();
    String data[] = line.split(" ");
    array = new int[data.length];

    minVal = Integer.parseInt(data[0]);
    for (int i = 0; i < data.length; i ++) {
      int num = Integer.parseInt(data[i]);
      array[i] = num;
      if (num < minVal) {
        minVal = num;
        minId = i;
      }
    }

    while (true) {
      res = doSubtract();
      if (res == -1) {
        System.out.println("NO");
        return;
      } else if (res == 0) {
        System.out.println("YES");
        return;
      }
    }
  }

  public static int doSubtract() {
    int i = minId;
    int res = 0;
    minVal = array[0];
    minId = 0;
    for (int j = 0; j < array.length; j++) {
      array[i] = array[i] - (j + 1);
      if (array[i] < 0) {
        return -1;
      } else if (array[i] > 0) {
        res = 1;
      }
      int v = array[i];
      if (v < minVal) {
        minVal = v;
        minId = i;
      }
      if (i == (array.length - 1)) {
        i = 0;
      } else {
        i = i + 1;
      }
    }
    return res;
  }

}

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

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

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


import java.util.ArrayList;
import java.util.*;
public class Main {
	static Scanner sc=new Scanner(System.in);
	public static void main(String[] args) {
		ArrayList<Integer> a=new ArrayList<Integer>();
		int n=sc.nextInt();
		int count=0;
		for (int i=0;i<n;i++){
			int temp=sc.nextInt();
			if(a.indexOf(temp)==-1){
				a.add(temp);
			}
		}
		int l=a.size();
		if(l%2==0){
			System.out.println(l-1);
		}
		else{
			System.out.println(l);
		}

	}

}

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

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7

Submitted source-code file size, in bytes.

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

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


import java.util.*;

/**
 * Created by sonetsuyoshi on 2016/07/31.
 */
public class Main {

    static class Node {
        int id;
        List<Node> children;
        Node(int id) {
            this.id = id;
            this.children = new ArrayList<>();
        }

        public String toString() {
            return id + ": " + children;
        }

        public int minDepth() {
            if(children.size() == 0) return 0;

            int minDepth = 0;
            for(Node child: children) {
                int depth = child.minDepth();
                minDepth = Math.max(child.minDepth(), minDepth);
            }
            return Math.max(minDepth + 1, children.size());
        }
    }

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

        Node[] nodes = new Node[N];
        for(int i = 0 ; i < N; i++) {
            nodes[i] = new Node(i);
        }

        for(int i = 1; i < N; i++) {
            int id = sc.nextInt() - 1;
            Node child = nodes[i];
            Node parent = nodes[id];
            parent.children.add(child);
        }

        System.out.println(nodes[0].minDepth());
    }
}

Score : 800 points

Problem Statement

N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament.
For some reasons, the tournament may not be "fair" for all the contestants.
That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The structure of the tournament is formally described at the end of this statement.

After each match, there were always one winner and one loser. The last contestant standing was declared the champion.

Figure: an example of a tournament

For convenience, the contestants were numbered 1 through N. The contestant numbered 1 was the champion, and the contestant numbered i(2 ≦ i ≦ N) was defeated in a match against the contestant numbered a_i.

We will define the depth of the tournament as the maximum number of the matches that must be played in order to win the championship over all the contestants.

Find the minimum possible depth of the tournament.

The formal description of the structure of the tournament is as follows. In the i-th match, one of the following played against each other:

Two predetermined contestants

One predetermined contestant and the winner of the j-th match, where j(j<i) was predetermined

The winner of the j-th match and the winner of the k-th match, where j and k (j,k<i, j ≠ k) were predetermined

Such structure is valid structure of the tournament, if and only if no contestant who has already been defeated in a match will never play in a match, regardless of the outcome of the matches.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i ≦ N(2 ≦ i ≦ N)

It is guaranteed that the input is consistent (that is, there exists at least one tournament that matches the given information).

Input

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

N
a_2
:
a_N

Output

Print the minimum possible depth of the tournament.

Sample Input 1

5
1
1
2
4

Sample Output 1

3

The following tournament and the result of the matches are consistent with the given information:

In the first match, contestants 4 and 5 played against each other, and contestant 4 won.

In the second match, contestants 2 and 4 played against each other, and contestant 2 won.

In the third match, contestants 1 and 3 played against each other, and contestant 1 won.

In the fourth match, contestants 1 and 2 played against each other, and contestant 1 won.

The depth of this tournament is 3, since contestant 5 must play three matches in order to win the championship.
There is no tournament with depth 2 or less that is consistent with the given information, thus the output should be 3.

Sample Input 2

7
1
2
1
3
1
4

Sample Output 2

3

Sample Input 3

4
4
4
1

Sample Output 3

3


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

class Main {

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

        try {

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

            String[] inputString = br.readLine().split(" ");
            int firstRectangleHeight = Integer.parseInt(inputString[0]);
            int firstRectangleWidth = Integer.parseInt(inputString[1]);
            int secondRectangleHeight = Integer.parseInt(inputString[2]);
            int secondRectangleWidth = Integer.parseInt(inputString[3]);

            int areaOfAFirstRectangle = firstRectangleHeight * firstRectangleWidth;
            int areaOfASecondRectangle = secondRectangleHeight * secondRectangleWidth;

            if (areaOfAFirstRectangle >= areaOfASecondRectangle) {
                System.out.println(areaOfAFirstRectangle);
            } else {
                System.out.println(areaOfASecondRectangle);
            }

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

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int A = Integer.parseInt(scanner.next());
        int B = Integer.parseInt(scanner.next());
        int C = Integer.parseInt(scanner.next());
        int D = Integer.parseInt(scanner.next());

        scanner.close();

        int abArea = A * B;
        int cdArea = C * D;

        int maxArea = Math.max(abArea, cdArea);
        System.out.println(maxArea);
    }
}


import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int number;
        number =input.nextInt();
        int sum=0;
        int max=0,temp;
        String s=input.next();
        for(int i=0;i<number;i++)
        {
            if(s.charAt(i)=='I')
            {
                sum++;
                if(max<sum)
                {
                    max=sum;
                }
            }
            else {
                sum--;
                if (max<sum)
                    max=sum;
            }
        }
        System.out.println(max);
    }

}

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

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

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		String S = scan.next();
		int an = 0;
		int b = 0;
        for(int i=0 ;i<a;i++ ){

        	if('I'==S.charAt(i)){
        		an++;
        	}else{
        		an--;
        	}

        	if(b<an){
        		b=an;
        	}
        }
        System.out.println(b);
    }
}


import java.util.*;

public class Main {
  public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    StringBuilder s = new StringBuilder(sc.next());
    s.replace(5,6," ");
    s.replace(13,14," ");
    System.out.println(s);
  }
}

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

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

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sx = scanner.nextInt();
        int sy = scanner.nextInt();
        int tx = scanner.nextInt();
        int ty = scanner.nextInt();

        int dv = ty-sy;
        int dx = tx-sx;

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < dv; i++) {
            builder.append("U");
        }
        for (int i = 0; i < dx; i++) {
            builder.append("R");
        }
        for (int i = 0; i < dv; i++) {
            builder.append("D");
        }
        for (int i = 0; i < dx; i++) {
            builder.append("L");
        }

        builder.append("L");
        for (int i = 0; i <= dv; i++) {
            builder.append("U");
        }
        for (int i = 0; i <= dx; i++) {
            builder.append("R");
        }
        builder.append("DR");
        for (int i = 0; i <= dv; i++) {
            builder.append("D");
        }
        for (int i = 0; i <= dx; i++) {
            builder.append("L");
        }
        builder.append("U");
        System.out.println(builder.toString());
    }
}

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


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

public class Main {

    void solve() throws IOException {
        int N = ni();
        int M = ni();
        DiGraph graph = new DiGraph(N);
        for (int i = 0; i < M; i++) {
            int a = ni()-1;
            int b = ni()-1;
            int c = ni();
            graph.addEdge(a, b, c);
            graph.addEdge(b, a, c);
        }
        int[][] used = new int[N][N];
        for (int s = 0; s < N; s++) {
            int[] prev = graph.dijkstra(s);
            int[] visited = new int[N];
            for (int i = 0; i < N; i++) {
                if(i!=s){
                    int now = i;
                    while(now!=s){
                        used[now][prev[now]] = 1;
                        used[prev[now]][now] = 1;
                        now = prev[now];
                    }
                }
            }
        }
        long ans = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                ans += used[i][j];
            }
        }
        out.println(M - ans/2);
    }

    class DiGraph {
        ArrayList<ArrayList<Edge>> graph = new ArrayList<>();
        int V;
        int[] visited;
        int[] hasSycle;
        public DiGraph(int numNode){
            this.V = numNode;
            for (int i = 0; i < numNode; i++) {
                this.graph.add(new ArrayList<>());
            }
            visited = new int[V];
            Arrays.fill(visited, -1);
            hasSycle = new int[V+1];
        }
        public void addEdge(int u, int v, int c){
            this.graph.get(u).add(new Edge(u,v,c));
        }
        public int[] dijkstra(int i){
            long[] res = new long[V];
            int[] prev = new int[V];
            prev[i] = i;
            Arrays.fill(res, Long.MAX_VALUE);
            PriorityQueue<Pair> que = new PriorityQueue<>((x,y)->x.cost.compareTo(y.cost));
            res[i] = 0;
            que.add(new Pair(i, 0));
            while(que.size()>0){
                Pair current = que.poll();
                for (Edge e : graph.get(current.node_id)) {
                    long newcost = current.cost + e.cost;
                    if(res[e.to] > newcost){
                        res[e.to] = newcost;
                        prev[e.to] = current.node_id;
                        que.add(new Pair(e.to, newcost));
                    }
                }
            }
            return prev;
        }
        public int countComponents(){
            Arrays.fill(visited, -1);
            Arrays.fill(hasSycle, 0);
            int count = 0;
            for (int i = 0; i < V; i++) {
                if(visited[i]==-1){
                    dfs(i, -1, count);
                    count++;
                }
            }
            // System.out.println(Arrays.toString(visited));
            // System.out.println(Arrays.toString(hasSycle));
            return count;
        }
        public int countTreeComponents(){
            int numComponent = countComponents();
            int countTree = 0;
            for (int i = 0; i < numComponent; i++) {
                if(hasSycle[i]==0) countTree++;
            }
            return countTree;
        }

        void dfs(int state, int prev, int count){
            visited[state] = count;
            for (Edge e : graph.get(state)) {
                if(e.to == prev) continue;
                if(visited[e.to] >= 0){
                    hasSycle[count] = 1;
                }else{
                    dfs(e.to, state, count);
                }
            }
        }
        class Edge{
            int from;
            int to;
            int cost;
            public Edge(int from, int to, int cost){
                this.from = from;
                this.to = to;
                this.cost = cost;
            }
        }
        class Pair{
            Integer node_id;
            Long cost;
            public Pair(int node_id, long cost){
                this.node_id = node_id;
                this.cost = cost;
            }
        }
    }

    final int mod = 1000000007;
    final BigInteger MOD = BigInteger.valueOf(mod);

    int mul(int x, int y){
        int val = (int)((x * 1L * y) % mod);
        return val>=0 ? val : val+mod;
    }
    int add(int x, int y) {
        x += y;
        if(x < 0) x += mod;
        if(x>=mod) x -= mod;
        return x;
    }
    int sub(int x, int y){
        x = add(x,mod-y);
        if(x < 0) x += mod;
        if(x>=mod) x -= mod;
        return x;
    }
    String ns() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine(), " ");
        }
        return tok.nextToken();
    }

    int ni() throws IOException {
        return Integer.parseInt(ns());
    }

    long nl() throws IOException {
        return Long.parseLong(ns());
    }

    double nd() throws IOException {
        return Double.parseDouble(ns());
    }

    String[] nsa(int n) throws IOException {
        String[] res = new String[n];
        for (int i = 0; i < n; i++) {
            res[i] = ns();
        }
        return res;
    }

    int[] nia(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = ni();
        }
        return res;
    }

    long[] nla(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = nl();
        }
        return res;
    }

    static BufferedReader in;
    static PrintWriter out;
    static StringTokenizer tok;

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        tok = new StringTokenizer("");
        Main main = new Main();
        main.solve();
        out.close();
    }
}

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

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

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

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.TreeSet;

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

    int n = sc.nextInt();
    int m = sc.nextInt();

    int[][] graph = new int[n][n];
    for(int i = 0; i< n; i++){
      for(int j = 0; j < n; j++){
        if(i == j){
          graph[i][j] = 0;
        }else{
          graph[i][j] = 1000001;
        }
      }
    }

    for(int i = 0; i < m; i++){
      int a = sc.nextInt() - 1;
      int b = sc.nextInt() - 1;
      int c = sc.nextInt();
      graph[a][b] = c;
      graph[b][a] = c;
    }

    int[][] shortest = new int[n][n];
    for(int i = 0; i < n; i++){
      for(int j = 0; j < n; j++){
        shortest[i][j] = graph[i][j];
      }
    }

    //わーしゃるふろいど
    for(int i = 0; i < n; i++){
      for(int j = 0; j < n; j++){
        for(int k = 0; k < n; k++){
          if(shortest[j][k] > shortest[j][i] + shortest[i][k]){
            shortest[j][k] = shortest[j][i] + shortest[i][k];
            shortest[k][j] = shortest[j][i] + shortest[i][k];
          }
        }
      }
    }

    int count = 0;
    for(int i = 0; i < n; i++){
      for(int j = i + 1; j < n; j++){
        if(graph[i][j] > shortest[i][j] && graph[i][j] <= 1000){//<=1000で、辺があるかどうか判定(条件より)
          count++;
        }
      }
    }

    System.out.println(count);

  }

 //ここからテンプレ
  static class InputReader {
      private InputStream stream;
      private byte[] buf = new byte[1024];
      private int curChar;
      private int numChars;
      private SpaceCharFilter filter;

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

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

      public String nextStr() {
        int c = next();
        while(isSpaceChar(c)){c = next();}
        StringBuffer str = new StringBuffer();
        do{
          str.append((char)c);
          c = next();
        }while(!isSpaceChar(c));
        return str.toString();
      }

      public char nextChar() {
        int c = next();
        while(isSpaceChar(c)){c = next();}
        char ret;
        do{
          ret = (char)c;
          c = next();
        }while(!isSpaceChar(c));
        return ret;
      }

      public int nextInt() {
          int c = next();
          while (isSpaceChar(c))
              c = next();
          int sgn = 1;
          if (c == '-') {
              sgn = -1;
              c = next();
          }
          int res = 0;
          do {
              if (c < '0' || c > '9')
                  throw new InputMismatchException();
              res *= 10;
              res += c - '0';
              c = next();
          } while (!isSpaceChar(c));
          return res * sgn;
      }

      public boolean isSpaceChar(int c) {
          if (filter != null)
              return filter.isSpaceChar(c);
          return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
      }

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


import java.util.Scanner;

public class Main {

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

	    long x=gl();
	    long y=gl();

	    long n=0;
	    if(x>y) {
	    	if(x*y>0) {
	    		n=x-y+2;
	    	} else if(x*y<=0) {
	    		n=1+Math.abs(Math.abs(x)-Math.abs(y));
	    	}
	    } else {
	    	if(x*y>0) {
	    		n=y-x;
	    	} else if(x*y<0) {
	    		n=1+Math.abs(Math.abs(x)-Math.abs(y));
	    	} else {
	    		n=Math.abs(x-y);
	    	}
	    }

        System.out.println(n);

		//System.out.println();
	}

	// 文字列として入力を取得
	public static String gs() {
		return scanner.next();
	}

	// intとして入力を取得
	public static int gi() {
		return Integer.parseInt(scanner.next());
	}

	// longとして入力を取得
	public static long gl() {
		return Long.parseLong(scanner.next());
	}

	// doubleとして入力を取得
	public static double gd() {
		return Double.parseDouble(scanner.next());
	}
}

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

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

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


import java.util.*;
public class Main{
    public static void main(String... args){
       Scanner scan = new Scanner(System.in);
       long x = scan.nextLong();
       long y = scan.nextLong();

       long res = 0;

       if(x < 0 && y < 0){
           if(y < x){
               res+=2;
           }
           x*=(-1);
           y*=(-1);
       }else if(y < 0){
           y*=(-1);
           res++;
       }else if(x < 0){
           x*=(-1);
           res++;
       }else if(y < x){
           res+=2;
       }

       if(x>0 && y == 0){
           res--;
       }else if(x<0 && y==0){
           res--;
       }

       res+= Math.max(x,y)-Math.min(x,y);

       System.out.println(res);
    }
}


import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong();
		boolean plus = sc.next().equals("+");
		long b = sc.nextLong();
		System.out.println(plus ? a + b : a - b);
	}
}

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		int A = Integer.parseInt(scn.next());
		String op = scn.next();
		int B = Integer.parseInt(scn.next());

		if (op.equals("+")) {
			System.out.println(A + B);
		} else if (op.equals("-")) {
			System.out.println(A - B);
		}
	}
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		try (Scanner sc = new Scanner(System.in)) {
			int n = sc.nextInt();
			int[] t = new int[n];
			int sum = 0;
			for(int i = 0 ; i < n ; i++) {
				t[i] = sc.nextInt();
				sum += t[i];
			}
			int m = sc.nextInt();
			int[] p = new int[m];
			int[] x = new int[m];
			for(int i = 0 ; i < m ; i++) {
				p[i] = sc.nextInt();
				x[i] = sc.nextInt();
			}
			for(int i = 0 ; i < m ; i++) {
				System.out.println(sum - (t[p[i] - 1] - x[i]));
			}
		}

	}

}

Score : 200 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

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

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.

If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30


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

		String[] square = new String[h];
		for (int i = 0; i < square.length; i++) {
			square[i] = sc.next();
		}

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


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

public class Main {
	class Pair{
		int a;
		int b;
		Pair(int a,int b){
			this.a=a;
			this.b=b;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + getOuterType().hashCode();
			result = prime * result + a;
			result = prime * result + b;
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (!getOuterType().equals(other.getOuterType()))
				return false;
			if (a != other.a)
				return false;
			if (b != other.b)
				return false;
			return true;
		}
		private Main getOuterType() {
			return Main.this;
		}
	}
	public static void main(String[] args) {
		Main main = new Main();
		main.run();
	}

	ArrayList<ArrayList<Integer>> klist;
	ArrayList<ArrayList<Integer>> llist;
	boolean kused[];
	boolean lused[];
	int kcolor[];
	int lcolor[];
	public void run() {
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		int k=sc.nextInt();
		int l=sc.nextInt();
		klist = new ArrayList<ArrayList<Integer>>();
		llist = new ArrayList<ArrayList<Integer>>();
		kused = new boolean[n+1];
		lused = new boolean[n+1];
		kcolor = new int[n+1];
		lcolor = new int[n+1];
		for(int i=0; i<=n; i++) {
			klist.add(new ArrayList<Integer>());
			llist.add(new ArrayList<Integer>());
		}
		for(int i=0; i<k; i++) {
			int p=sc.nextInt();
			int q=sc.nextInt();
			klist.get(p).add(q);
			klist.get(q).add(p);
		}
		for(int i=0; i<l; i++) {
			int r=sc.nextInt();
			int s=sc.nextInt();
			llist.get(r).add(s);
			llist.get(s).add(r);
		}

		int color=1;
		for(int i=1; i<=n; i++) {
			if(!kused[i]) {
				dfs(i, klist, kused, kcolor, color);
			}
			if(!lused[i]) {
				dfs(i, llist, lused, lcolor, color);
			}
			color++;
		}
		Map<Pair , Integer> m = new HashMap<>();

		for(int i=1; i<=n; i++) {
			Pair p = new Pair(kcolor[i], lcolor[i]);
			m.put(p, m.get(p) != null ? m.get(p)+1 : 1);
		}
		for(int i=1; i<=n; i++) {
			if(i>1)System.out.print(" ");
			Pair p = new Pair(kcolor[i], lcolor[i]);
			System.out.print(m.get(p));
		}
		System.out.println();
		sc.close();
	}

	public void dfs(int s, ArrayList<ArrayList<Integer>> list, boolean[] used, int c[], int color) {
		ArrayDeque<Integer> g = new ArrayDeque<Integer>();
		g.add(s);
		used[s]=true;
		c[s]=color;
		while(!g.isEmpty()) {
			int p = g.pop();
			ArrayList<Integer> k = list.get(p);
			for(int i=0; i<k.size(); i++) {
				int q=k.get(i);
				if(p != q && ! used[q]) {
					g.add(q);
					c[q]=color;
					used[q]=true;
				}
			}
		}
	}
}

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

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

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


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

class Main{
	public static void main(String[] args) throws Exception{
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int k = scan.nextInt();
		int l = scan.nextInt();

		ArrayList<ArrayList<Integer>> load = new ArrayList<>(n);
		ArrayList<ArrayList<Integer>> rail = new ArrayList<>(n);
		for(int i = 0; i < n; i++) {
			load.add(new ArrayList<Integer>());
			rail.add(new ArrayList<Integer>());
		}

		for(int i = 0; i < k; i++) {
			int p = scan.nextInt()-1;
			int q = scan.nextInt()-1;
			load.get(p).add(q);
			load.get(q).add(p);
		}

		for(int i = 0; i < l; i++) {
			int p = scan.nextInt()-1;
			int q = scan.nextInt()-1;
			rail.get(p).add(q);
			rail.get(q).add(p);
		}

		boolean[] flagMap = new boolean[n];
		int groupNum = 0;
		int[] loadGroup = new int[n];
		for(int i = 0; i < n; i++) {
			int result = check(load,i,flagMap,groupNum,loadGroup);
			if(result>0) {
				groupNum++;
			}
		}

		flagMap = new boolean[n];
		groupNum = 0;
		int[] railGroup = new int[n];
		for(int i = 0; i < n; i++) {
			int result = check(rail,i,flagMap,groupNum,railGroup);
			if(result>0) {
				groupNum++;
			}
		}
/*
		for(int i = 0; i < n; i++) {
			System.out.printf("ldGrp:%d,rlGrp:%d\n",loadGroup[i],railGroup[i]);
		}
*/
		HashMap<Long,Integer> map = new HashMap<>();
		for(int i = 0; i < n; i++) {
			long hash = getHash(railGroup[i],loadGroup[i]);
			if(map.containsKey(hash)) map.put(hash, map.get(hash)+1);
			else map.put(hash, 1);
		}

		for(int i = 0; i < n; i++) {
			//System.out.println(getHash(railGroup[i],loadGroup[i]));
			System.out.println(map.get(getHash(railGroup[i],loadGroup[i])));
		}
	}

	static long getHash(int x, int y) {
		return x*1000000L+(long)y;
	}

	static int check(ArrayList<ArrayList<Integer>> list, int start, boolean[] flagMap, int groupNum, int[] group) {
		if(flagMap[start]) return 0;
		flagMap[start] = true;
		group[start] = groupNum;
		int sum = 0;
		for(int next : list.get(start)) {
			sum += check(list,next,flagMap,groupNum,group);
		}
		return 1 + sum;
	}
}


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

public class Main {

    static BufferedReader in;
    static PrintWriter out;
    static StringTokenizer tok;

    void solve() throws IOException {
        int n = ni(), k = ni(), l = ni();

        int[] p = new int[k];
        int[] q = new int[k];
        for (int i = 0; i < k; i++) {
            p[i] = ni() - 1;
            q[i] = ni() - 1;
        }
        int[] r = new int[l];
        int[] s = new int[l];
        for (int i = 0; i < l; i++) {
            r[i] = ni() - 1;
            s[i] = ni() - 1;
        }

        UnionFind uf1 = new UnionFind(n);
        for (int i = 0; i < k; i++) {
            uf1.union(p[i], q[i]);
        }

        UnionFind uf2 = new UnionFind(n);
        for (int i = 0; i < l; i++) {
            uf2.union(r[i], s[i]);
        }

        ArrayList<ArrayList<Integer>> groups = uf2.groups();

        int[] ans = new int[n];

        for (int i = 0; i < groups.size(); i++) {
            ArrayList<Integer> group = groups.get(i);
            Collections.sort(group, (x1, x2) -> uf1.root(x1) - uf1.root(x2));
            for (int j = 0; j < group.size(); j++) {
                int idx = j;
                int cnt = 1;
                while (idx < group.size() - 1 && uf1.isConnected(group.get(j), group.get(idx + 1))) {
                    idx++;
                    cnt++;
                }
                for (int m = j; m <= idx; m++) {
                    ans[group.get(m)] = cnt;
                }
                j = idx;
            }
        }

        for (int i = 0; i < n; i++) {
            if (i > 0) out.print(" ");
            out.print(ans[i]);
        }
        out.println();
    }

    class UnionFind {
        private int[] parent;

        UnionFind(int size) {
            parent = new int[size];
            Arrays.fill(parent, -1);
        }

        public boolean union(int x, int y) {
            x = root(x);
            y = root(y);
            if (x != y) {
                if (parent[y] < parent[x]) {
                    int tmp = y;
                    y = x;
                    x = tmp;
                }
                parent[x] += parent[y];
                parent[y] = x;
                return true;
            }
            return false;
        }

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

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

        public int size(int x) {
            return -parent[root(x)];
        }

        public ArrayList<ArrayList<Integer>> groups() {
            int n = parent.length;
            ArrayList<ArrayList<Integer>> g = new ArrayList<>();
            HashMap<Integer, Integer> hm = new HashMap<>();
            for (int i = 0; i < n; i++) {
                int r = root(i);
                if (!hm.containsKey(r)) {
                    hm.put(r, g.size());
                    g.add(new ArrayList<>());
                }
                g.get(hm.get(r)).add(i);
            }
            return g;
        }

        public String toString() {
            return Arrays.toString(parent);
        }
    }

    String ns() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine(), " ");
        }
        return tok.nextToken();
    }

    int ni() throws IOException {
        return Integer.parseInt(ns());
    }

    long nl() throws IOException {
        return Long.parseLong(ns());
    }

    double nd() throws IOException {
        return Double.parseDouble(ns());
    }

    String[] nsa(int n) throws IOException {
        String[] res = new String[n];
        for (int i = 0; i < n; i++) {
            res[i] = ns();
        }
        return res;
    }

    int[] nia(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = ni();
        }
        return res;
    }

    long[] nla(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = nl();
        }
        return res;
    }

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        tok = new StringTokenizer("");
        Main main = new Main();
        main.solve();
        out.close();
    }
}


import java.util.*;

public class Main{
      public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String str1 = sc.next();
            String str2 = sc.next();
            String str3 = sc.next();
            String[] str1a = str1.split("");
            String[] str2a = str2.split("");
            String[] str3a = str3.split("");
            System.out.println(str1a[0] + str2a[0] + str3a[0]);
            }
}

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

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

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		System.out.println("コンテスト名を入力してください。");

		Scanner scan = new Scanner(System.in);
		String a = scan.next();
		String b = scan.next();
		String c = scan.next();

		System.out.println(a.charAt(0)+"" + b.charAt(0)+"" + c.charAt(0));
	}

}


import java.util.Scanner;

public class Main {

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

		long a, b, x, count = 0;

		a = sc.nextLong();
		b = sc.nextLong();
		x = sc.nextLong();

		count = (b - a) / x + 1;
		if(a != 0 && a % x != 0)count = (b / x) - ((a - 1) / x);
		if(b == a && a % x != 0)count = 0;

		System.out.println(count);

		sc.close();
	}

}

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

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

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      ArrayList<Integer> one = nextIntArray();
      int N = one.get(0);
      int x = one.get(1);
      ArrayList<Integer> list = nextIntArray();
      long output = 0;
      for(int i = 1; i < N; i++){
        int mae = list.get(i - 1);
        int ato = list.get(i);
        if(mae + ato > x){
          int minus = (mae + ato) - x;
          output += minus;
          list.set(i, Math.max(0, list.get(i) - minus));
          if(ato < minus){
            minus -= ato;
            list.set(i - 1, Math.max(0, list.get(i - 1) - minus));
          }
        }
      }
      myout(output);
	}
	//Method addition frame start

	//Method addition frame end
}

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

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();

		String[] a;
		a = str.split(" ", 0);
		int n = Integer.parseInt(a[0]);
		int x = Integer.parseInt(a[1]);

		String str2 = br.readLine();
		String[] numstring = str2.split(" ", 0);
		int[] nums = new int[n];
		boolean[] numserased = new boolean[n];		//一つ前のループで消されたかどうかを調べる

		for(int i = 0; i < numstring.length; i++){
			nums[i] = Integer.parseInt(numstring[i]);
			numserased[i] = false;
		}

		int count = 0;		//キャンディをとった回数をカウント

		while(true){
			boolean out = true;
			boolean notover = true;
			ArrayList<Integer> indexs = new ArrayList<Integer>();		//
			ArrayList<Integer> overindexs = new ArrayList<Integer>();	//if文を満たさない連続した箱（重複している箱）の最初の箱の番号

			boolean overing = false;
			for(int i = 1; i < nums.length; i++){
				if(nums[i]+nums[i-1] > x){
					out = false;
					indexs.add(i);

					if(nums[i] != 0){

						//ここに連続してきていないなら
						if(i != nums.length-1 && notover){
							overing = true;
							overindexs.add(i);
							notover = false;
						}
					}
				}else{
					notover = true;
					if(overing){
						overing = false;
						overindexs.add(i-1);
					}
				}
			}

			if(overing)	overindexs.add(nums.length-1);
			if(out)	break;

			for(int i = 0; i < overindexs.size(); i += 2){
				int difference = overindexs.get(i+1) - overindexs.get(i);
				if(difference >=3){
					for(int j = 0; j < difference-2; j++){
						if(j % 2 == 0){
							nums[overindexs.get(i)+j]--;
							count++;
						}

						//indexsから同じ箱を指しているものを探す
						for(int k = 0; k < indexs.size(); k++)
							if(indexs.get(k) == overindexs.get(i)+j)	indexs.remove(k);
					}
				}else{
					for(int j = overindexs.get(i); j <= overindexs.get(i+1); j++){
						if(overindexs.size() != j){
							nums[j]--;
							count++;
						}

						for(int k = 0; k < indexs.size(); k++)
							if(indexs.get(k) == j)		indexs.remove(k);
					}
				}
			}

			for(int i = 0; i < indexs.size(); i++){
				if(!numserased[indexs.get(i)]){
					nums[indexs.get(i)]--;
					if(nums[indexs.get(i)-1] != 0) numserased[indexs.get(i)] = true;
				}else{
					nums[indexs.get(i)-1]--;
					numserased[indexs.get(i)] = false;
				}
				count++;
				indexs.remove(i);
			}
		}

		System.out.println(count);
		for(int i = 0; i < nums.length; i++)
			System.out.print(nums[i]+" ");
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

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

        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(is);
        List<String> mylist = new ArrayList<>();
        // 標準入力からの値を変数strinputに代入
        String strinput = reader.readLine();
        while (strinput != null) {

            mylist.add(strinput);
            strinput = reader.readLine();

        }

        String arr_temp[] = mylist.get(0).split(" ");
        int x = Integer.valueOf(arr_temp[0]);

        if (x == 1) {
            System.out.println(1);
        } else if (x == 2) {

            System.out.println(2);

        } else if (x == 3) {

            System.out.println(2);
            System.out.println(1);

        } else if (x == 4) {

            System.out.println(3);
            System.out.println(1);

        } else if (x == 5) {
            System.out.println(3);
            System.out.println(2);

        } else {
            if (x % 2 == 1) {
                int halfdata = x / 2;
                System.out.println(1);
                System.out.println(halfdata - 1);
                System.out.println(halfdata + 1);

            } else {
                int halfdata = x / 2;
                System.out.println(1);
                System.out.println(halfdata - 1);
                System.out.println(halfdata);
            }
        }
    }

}

Score : 300 points

Problem Statement

The problem set at CODE FESTIVAL 20XX Finals consists of N problems.

The score allocated to the i-th (1≦i≦N) problem is i points.

Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.

As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.

Determine the set of problems that should be solved.

Constraints

1≦N≦10^7

Partial Score

200 points will be awarded for passing the test set satisfying 1≦N≦1000.

Additional 100 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

Output

Among the sets of problems with the total score of N, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.

If there exists more than one such set, any of them will be accepted.

Sample Input 1

4

Sample Output 1

1
3

Solving only the 4-th problem will also result in the total score of 4 points, but solving the 1-st and 3-rd problems will lower the highest score of a solved problem.

Sample Input 2

7

Sample Output 2

1
2
4

The set \{3,4\} will also be accepted.

Sample Input 3

1

Sample Output 3

1


class UnionFind {
	private int[] table;
	private int[] rank;

	public UnionFind(int size) {
		this.table = new int[size];
		this.rank = new int[size];
		for (int i = 0; i < size; i ++) {
			this.table[i] = i;
			this.rank[i] = 1;
		}
	}

	public boolean isSame(int node1, int node2) {
		return find(node1) == find(node2);
	}

	public int find(int node) {
		if (table[node] == node) {
			return node;
		} else {
			return table[node] = find(table[node]);
		}
	}

	public void union(int node1, int node2) {
		int root1 = find(node1);
		int root2 = find(node2);

		if (rank[root1] < rank[root2]) {
			table[root1] = root2;
		} else if (rank[root1] > rank[root2]) {
			table[root2] = root1;
		} else if (root1 != root2) {
			table[root2] = root1;
			rank[root1] ++;
		}
	}
}
public class Main {

	private static void solve() {
		int n = ni();
		int m = ni();

		UnionFind uf = new UnionFind(n + m);
		for (int i = 0; i < n; i ++) {
			int k = ni();
			for (int j = 0; j < k; j ++) {
				uf.union(i, n + ni() - 1);
			}
		}
		int root = uf.find(0);
		for (int i = 0; i < n; i ++) {
			if (uf.find(i) != root) {
				System.out.println("NO");
				return;
			}
		}
		System.out.println("YES");
	}

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

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

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

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

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

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

	private static char[] ns() {
		return next().toCharArray();
	}

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

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

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

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

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

Score : 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+1<w) {
					if((ac[x][y+1]=='#')) {
						y++;
					}
				}

				if(x+1<h) {
					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.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int W = sc.nextInt();
		int H = sc.nextInt();
		int N = sc.nextInt();
		int a[][] = new int[H][W];
		for (int i=0;i<N;i++) {
			int x= sc.nextInt();
			int y= sc.nextInt();
			int b=sc.nextInt();
			if (b==1) {
				for (int k=0;k<H;k++) {
					for (int j=0;j<x;j++) {
						a[k][j]++;
					}
				}
			} else if (b==2) {
				for (int k=0;k<H;k++) {
					for (int j=x;j<W;j++) {
						a[k][j]++;
					}
				}
			} else if (b==3) {
				for (int k=0;k<y;k++) {
					for (int j=0;j<W;j++) {
						a[k][j]++;
					}
				}
			} else {
				for (int k=y;k<H;k++) {
					for (int j=0;j<W;j++) {
						a[k][j]++;
					}
				}
			}
		}
		int count=0;
		for (int i=0;i<H;i++) {
			for (int j =0;j<W;j++) {
				if (a[i][j]==0) {
					count++;
				}
			}
		}
		System.out.println(count);
	}
}

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

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

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

10 10 5
1 6 1
4 1 3
6 9 4
9 4 2
3 1 3

Sample Output 3

64


import java.util.Scanner;

public class Main {

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

		Field field = new Field(W, H);

		for (int i = 0; i < N; i++) {
			int x = sc.nextInt();
			int y = sc.nextInt();
			int a = sc.nextInt();
			field.draw(x, y, a);
		}

		System.out.println(field.calcWhiteArea());
	}

	static class Field {
		final int W, H;
		final boolean[] fieldArray;

		public Field(int W, int H) {
			this.fieldArray = new boolean[W * H];
			this.W = W;
			this.H = H;
			for (int i = 0; i < W * H; i++) {
				fieldArray[i] = true;
			}
		}

		public void draw(int x, int y, int a) {
			switch (a) {
			case 1:
				drawRect(0, x, 0, H);
				break;
			case 2:
				drawRect(x, W, 0, H);
				break;
			case 3:
				drawRect(0, W, 0, y);
				break;
			case 4:
				drawRect(0, W, y, H);
				break;
			}
		}

		private void drawRect(int x1, int x2, int y1, int y2) {
			for (int x = x1; x < x2; x++) {
				for (int y = y1; y < y2; y++) {
					drawPoint(x, y);
				}
			}
		}

		private void drawPoint(int x, int y) {
			this.fieldArray[x * H + y] = false;
		}

		public int calcWhiteArea() {
			int ans = 0;
			for (int i = 0; i < W * H; i++) {
				if (this.fieldArray[i]) {
					ans++;
				}
			}
			return ans;
		}
	}
}


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

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            pass System Test!
*/

public class Main {
  private static class Task {
    void solve(FastScanner in, PrintWriter out) throws Exception {
      char[] S = in.next().toCharArray();
      int cnt = 1;
      char cur = S[0];
      for (int i = 1; i < S.length; i++) {
        if (S[i] != cur) {
          cnt++;
          cur = S[i];
        }
      }
      out.println(cnt - 1);
    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) throws Exception {
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner();
    PrintWriter out = new PrintWriter(outputStream);
    Task solver = new Task();
    solver.solve(in, out);
    out.close();
  }
  private static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int bufferLength = 0;

    private boolean hasNextByte() {
      if (ptr < bufferLength) {
        return true;
      } else {
        ptr = 0;
        try {
          bufferLength = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (bufferLength <= 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 void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

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

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

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

    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][];
      for (int i = 0; i < n; i++) {
        map[i] = nextDoubleArray(m);
      }
      return map;
    }

    public int nextInt() {
      return (int) nextLong();
    }

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

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

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

    public char[][] nextCharMap(int n) {
      char[][] array = new char[n][];
      for (int i = 0; i < n; i++) array[i] = next().toCharArray();
      return array;
    }

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

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.util.Scanner;

public class Main {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    String s = sc.next();
    int i = 0;
    boolean ok = false;

    for (i = 0; i < s.length(); i++) {
      if (s.charAt(i) == 'C') {
        break;
      }
    }

    for (; i < s.length(); i++) {
      if (s.charAt(i) == 'F') {
        ok = true;
        break;
      }
    }

    if (ok) {
      System.out.println("Yes");
    } else {
      System.out.println("No");
    }

  }
}

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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
		String s = r.readLine();
		String[] parts = s.split(" ");
		int K = Integer.parseInt(parts[0]);
		int T = Integer.parseInt(parts[1]);
		s = r.readLine();
		parts = s.split(" ");
		int max = 0;
		for (int i = 0; i < T; i++) {
			int curr = Integer.parseInt(parts[i]);
			if (curr > max) {
				max = curr;
			}
		}
		boolean pre = false;
		int count = K - max;
		for (int i = 0; i < K; i++) {
			if (!pre && max > 0) {
				max--;
				pre = true;
			} else if (count > 0){
				pre = false;
				count--;
			}
		}
		System.out.println(max);
	}

}

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.util.StringTokenizer;

public class Main {

    final static int MOD = 1_000_000_007;

    static int N;
    static int[] T;
    static int[] A;

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        N = sc.nextInt();
        T = sc.nextIntArray(N);
        A = sc.nextIntArray(N);

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

    static long solve() {
        boolean[] TB = new boolean[N];
        TB[0] = true;
        for (int i = 1; i < N; i++) {
            if( T[i] > T[i-1] ) {
                TB[i] = true;

            } else if(T[i] == 1) {
                TB[i] = true;

            } else {
                TB[i] = false;
            }
        }

        boolean[] AB = new boolean[N];
        AB[N-1] = true;
        for (int i = N-2; i >= 0 ; i--) {
            if( A[i] > A[i+1] ) {
                AB[i] = true;

            } else if( A[i] == 1 ) {
                AB[i] = true;

            } else {
                AB[i] = false;
            }
        }

        long ans = 1;
        for (int i = 0; i < N; i++) {
            int t = T[i];
            int a = A[i];

            if( TB[i] && AB[i] ) {
                if( t != a ) {
                    return 0;
                }

            } else if( TB[i] || AB[i] ) {
                // nothing

            } else {
                ans = ans * Math.min(t, a) % MOD;
            }
        }

        return ans;
    }

    static class FastScanner {

        private BufferedReader reader;
        private StringTokenizer tokenizer;

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

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

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

            return tokenizer.nextToken("\n");
        }

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

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

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

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

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

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.util.Scanner;

public class Main {

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

		if(a==b && b==c){
			System.out.println("1");
		}else if(a==b | b==c | c==a){
			System.out.println("2");
		}else{
			System.out.println("3");
		}
	}

}

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.*;

public class Main {

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		long N = sc.nextLong();
		long K = sc.nextLong();
		long ans = K;
		for (int i = 1; i < N; i++) {
			ans *= K-1;
		}
		System.out.println(ans);
	}
}

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

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

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


import java.util.Scanner;

public class Main {

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

			for(int i = 0 ; i < N ; i++){
				A[i][0] = sc.nextLong();
				A[i][1] = sc.nextLong();
			}
			sc.close();
			long ans = 0;
			ans = A[0][0] + A[0][1];

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

				if(A[i][0]-A[i-1][0]>=0 && A[i][1]-A[i-1][1]>=0){
					ans+= (A[i][0]-A[i-1][0])+ (A[i][1]-A[i-1][1]);
				}
				else{
					long p = Math.max((long)Math.ceil((double)A[i-1][0]/A[i][0]), (long)Math.ceil((double)A[i-1][1]/A[i][1]));

					ans +=(A[i][0]*p - A[i-1][0]) + (A[i][1]*p-A[i-1][1]);
					A[i][0] = A[i][0]*p;
					A[i][1] = A[i][1]*p;

				}
			}

			System.out.println(ans);
	}
}

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.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static final PrintStream so = System.out;
    static final Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        char[] x = nsToChars();
        int len = x.length;

        int countST = 0;
        int countS = 0;
        for (int i = 0; i < len; i++) {
            if (x[i] == 'S') {
                countS++;

            } else if (countS > 0) {
                countS--;
                countST++;
            }
        }
        so.println(len - countST*2);
    }

    static int ni() {
        return sc.nextInt();
    }

    static long nl() {
        return sc.nextLong();
    }

    static char[] nsToChars() {
        return sc.next().toCharArray();
    }
}

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 {
	public static void main(String[] args) {
		Scanner str = new Scanner(System.in);
		String s = str.nextLine();
		int tcnt = 0, scnt = 0;
		for (int i = 0; i < s.length(); i++) {
			if (String.valueOf(s.charAt(i)).equals("S")) {
				scnt += 1;
			} else {
				if (scnt == 0) {
					tcnt += 1;
				} else {
					scnt -= 1;
				}
			}
		}
		System.out.println(tcnt + scnt);
		str.close();
	}
}


import java.util.*;
public class Main {

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

        StringBuffer s = new StringBuffer(sc.nextLine());
        int k = sc.nextInt();

            for(int i = 0;i<s.length()-1;i++){
                if(s.charAt(i) != 'a' && k - ( 26 - ( (int)s.charAt(i) - 97 ) ) >= 0){
                    k -= ( 26 - ( (int)s.charAt(i) - 97 ) );
                    s.setCharAt(i, 'a');
                }
            }
//        System.out.println(26-(int)'i' + 97);

        k = k % 26;
        if(s.charAt(s.length()-1) + k > 122){
            s.setCharAt(s.length()-1, (char)(s.charAt(s.length()-1) + k-26));
        }else{
            s.setCharAt(s.length()-1, (char)(s.charAt(s.length()-1) + k));
        }
        System.out.println(s);

//        System.out.println(100-('c'-96+21));
//        System.out.println(26-( (int)'o' - 97));

    }
}

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.io.IOException;
import java.util.*;

public class Main {

	public static void main(String[] args) {

		int num[]=new int[100001];int j=0;int spaceFound=0;int total=0;int fin=0;
		o1:do
		{
			try {
				num[j]=System.in.read();
			} catch (IOException e) {
				break o1;
			}
			if(num[j]=='\n'){
				total=j-1;
				break o1;
			}
			j++;
		}
		while(true);

		Scanner s = new Scanner(System.in);

		int K=Integer.parseInt(s.next());

		for(j=0;j<total;j++)
		{
			num[j]-=97;
		}

		//base 26 start from0
		j=0;
		o:while(K>0)
		{
			if(j==total-1)
			{
				K--;
				num[j]=(1+num[j])%26;
			}
			else
			{
				if(K<26-num[j])
				{
					j++;
					continue o;
				}//else
				K-=26-num[j];
				num[j]=0;
				j++;
			}
		}

		for(j=0;j<total;j++)
		{
			System.out.print((char)(num[j]+97));
		}
	}

}