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

public class Main {
    static boolean[][] used;
    static int[] ans;
    public static void main(String[] args) throws Exception {
        long max = 100000 * 20000000000L;
        FastScanner sc = new FastScanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        int k = sc.nextInt();
        long[] a = sc.nextLongArray(n);
        long ans = 0;
        for(int i = 0; i <= k; i++){
            for(int j = 0; j <= k-i; j++){
                if(i+j > n) continue;
                long now = 0;
                int d = k-i-j;
                ArrayList<Long> li = new ArrayList<>();
                for(int l = 1; l <= i; l++){
                    now += a[l-1];
                    li.add(a[l-1]);
                }
                for(int r = 1; r <= j; r++){
                    now += a[n-r];
                    li.add(a[n-r]);
                }
                Collections.sort(li);
                for(int v = 0; v < d; v++){
                    if(v >= li.size()) break;
                    if(li.get(v) >= 0) break;
                    now -= li.get(v);
                }
                ans = Math.max(ans,now);
            }
        }
        System.out.println(ans);
    }
}

class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;
    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

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

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

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

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

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

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

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

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Roadwork
 */
public class Main {

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

            int[][] W = new int[N][3];
            for (int i = 0; i < N; i++) {
                W[i][0] = sc.nextInt();
                W[i][1] = sc.nextInt();
                W[i][2] = sc.nextInt();
            }

            Arrays.sort(W, (o1, o2) -> Integer.compare(o1[2], o2[2]));

            List<Integer> D = new ArrayList<Integer>();
            Map<Integer, Integer> index = new HashMap<>();
            for (int i = 0; i < Q; i++) {
                int d = sc.nextInt();
                D.add(d);
                index.put(d, i);
            }

            int[] A = new int[Q];
            Arrays.fill(A, -1);

            for (int i = 0; i < N; i++) {
                int s = W[i][0];
                int t = W[i][1];
                int x = W[i][2];

                int pos1 = Collections.binarySearch(D, s - x);
                if (pos1 < 0) {
                    pos1 = -(pos1 + 1);
                }

                int pos2 = Collections.binarySearch(D, t - x);
                if (pos2 < 0) {
                    pos2 = -(pos2 + 1);
                }

                //System.out.println(s + " " + t + " " + x + " " + pos1 + " " + pos2 + " " + D);

                if (pos1 == pos2) {
                    continue;
                }

                for (int p = pos1; p < pos2; p++) {
                    int q = D.remove(pos1);
                    A[index.get(q)] = x;
                }
            }

            StringBuilder ans = new StringBuilder();
            for (int a : A) {
                ans.append(a).append("\n");
            }

            System.out.print(ans.toString());
        }
    }

}

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

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.

Submitted source-code file size, in bytes.

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

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


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int a = sc.nextInt();
		// スペース区切りの整数の入力
		int b = sc.nextInt();
		// 出力

		if(b%2==0) {
			if ( a>=0 && a<6 )  {
				System.out.println(0);
			} else if ( a>=6 && a<12 ){
				System.out.println(b/2);
			} else if ( a>=13 && a<= 100){
				System.out.println(b);
			} else {
			}
		}
	}
}

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


import java.util.*;

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

        if(nennrei > 12){
          System.out.println(b);
        }else if(nennrei < 6){
          System.out.println(0);
        }else{
          System.out.println(b/2);
        }
    }
}


import java.util.*;

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

        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt();
        int d = sc.nextInt();
        int x2000 = sc.nextInt();

        int x2001 = r*x2000 - d;
        int x2002 = r*x2001 - d;
        int x2003 = r*x2002 - d;
        int x2004 = r*x2003 - d;
        int x2005 = r*x2004 - d;
        int x2006 = r*x2005 - d;
        int x2007 = r*x2006 - d;
        int x2008 = r*x2007 - d;
        int x2009 = r*x2008 - d;
        int x2010 = r*x2009 - d;
        System.out.println(x2001);
        System.out.println(x2002);
        System.out.println(x2003);
        System.out.println(x2004);
        System.out.println(x2005);
        System.out.println(x2006);
        System.out.println(x2007);
        System.out.println(x2008);
        System.out.println(x2009);
        System.out.println(x2010);
    }
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


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

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int n = Integer.parseInt(sc.next());
        int m = Integer.parseInt(sc.next());

        PriorityQueue<Integer> a = new PriorityQueue<>();
        for(int i = 0; i < n; i++){
            a.offer(Integer.parseInt(sc.next()));
        }

        List<BC> list = new ArrayList<>();
        for(int i = 0; i < m; i++){
            list.add(new BC(Integer.parseInt(sc.next()), Integer.parseInt(sc.next())));
        }
        Collections.sort(list);

        int count = 0;
        int b, c;
        for(int i = 0; i < m; i++){
            b = list.get(i).b;
            c = list.get(i).c;
            for(int j = 0; j < b; j++){
                if(a.peek() >= c){
                    break;
                }
                a.poll();
                a.offer(c);
                count++;
                if(count >= n){
                    break;
                }
            }
            if(c <= a.peek() || count >= n){
                break;
            }
        }

        long ans = 0;
        for(int i = 0; i < n; i++){
            ans += a.poll();
        }
        System.out.println(ans);
    }
}

class BC implements Comparable<BC>{
    int b;
    int c;

    BC(int b, int c){
        this.b = b;
        this.c = c;
    }

    @Override
    public int compareTo(BC bc) {

        if(this.c > bc.c){
            return -1;
        }else if(this.c < bc.c){
            return 1;
        }else{
            return 0;
        }
    }
}

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

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


import java.util.*;
class Main {
    public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int n = Integer.parseInt(sc.next());
	int m = Integer.parseInt(sc.next());
	long[] a = new long[n];
	long[] sum = new long[n+1];

	for(int i = 0; i<n; i++) {
	    a[i] = Long.parseLong(sc.next());
	}
	Arrays.sort(a);

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

	long max = sum[n];
	for(int i = 0; i<m; i++) {
	    int b = Integer.parseInt(sc.next());
	    long c = Long.parseLong(sc.next());

	    if(c<=a[0]) continue;

	    //nibutan?
	    for(int j = b; j>0; j--) {
		if(a[j-1]>c) continue;
		//System.out.println("sumn: " + sum[n] + " sumb " + sum[j] + " cb " + (c*j) + " max? " + (sum[n]-sum[j]+c*j));
		max = Math.max(max, sum[n]-sum[j]+c*j);

		for(int k = 0; k<j; k++) a[k] = c;
		break;
	    }
	    Arrays.sort(a);
	    for(int j = 0; j<n; j++) {
		//System.out.print(a[j] + " ");
		sum[j+1] = a[j] + sum[j];
	    }
	    //System.out.println();
	    max = sum[n];
	}
	System.out.println(max);

    }
}


import java.util.*;

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

    int s=sc.nextInt();
		s+=10000;
		int k=s%100; //下２桁
		int t=s/100; //上２桁

		if((k>12 || k==0) && t<=112){
			System.out.println("MMYY");
		}else if(k<=12 && k!=0 && (t>112 || t==100)){
			System.out.println("YYMM");
		}else if(k<=12 && t<=112 && k!=0 && t!=0){
			System.out.println("AMBIGUOUS");
		}else{
			System.out.println("NA");
		}

	}
}

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


import java.math.BigDecimal;
import java.util.Scanner;

public class Main {

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

    public static void main(String[] args) {

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

        BigDecimal ans = new BigDecimal(0);

        BigDecimal nbd = new BigDecimal(n);
        BigDecimal add;
        for (int i=1; i <= n; i++) {
            add = new BigDecimal("0.5").pow(countPowOf2(k, i)).divide(nbd, 12, BigDecimal.ROUND_HALF_UP);

            ans = ans.add(add);
        }

        System.out.println(ans.toString());
    }

    private static int countPowOf2(int target, int orig) {
        int pow = 0;
        while (orig < target) {
            orig *= 2;
            pow++;
        }
        return pow;
    }

}

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void debug(String str) {
        boolean debug = false;
        if (debug == false) {
            return;
        }
        System.out.println(str);
    }

    public static class Edge {
        int u;
        int v;
        int w;

        public Edge(int u, int v, int w) {
            this.u = u;
            this.v = v;
            this.w = w;

        }
    }

    public static void main(String[] args) {

        int N;
        HashMap<Integer,List<Edge>> set;

        try (Scanner sc = new Scanner(System.in)) {
            N = sc.nextInt();
            set = new HashMap<>();
            for (int i = 0; i < N - 1; i++) {
                int u = sc.nextInt();
                int v = sc.nextInt();
                int w = sc.nextInt();
                Edge e = new Edge(u, v, w);
                setSet(set,e,u);
                setSet(set,e,v);
            }
        }
        int[] distans = new int[N];
        HashSet<Edge> visited = new HashSet<>();
        Deque<Integer> queue = new ArrayDeque<>();
        queue.push(1);
        distans[0] = 0;
        Integer target;
        while((target = queue.pollFirst()) != null){
            List<Edge> list = set.get(target);
            for(Edge e : list){
                if(visited.contains(e)){
                    continue;
                }else{
                    if(e.u != target && e.v == target){
                        queue.addLast(e.u);
                        distans[e.u  -1] = distans[target-1] + e.w;
                        debug(e.u+":" + distans[e.u  -1] );
                    }else if(e.v != target && e.u == target){
                        queue.addLast(e.v);
                        distans[e.v  -1] = distans[target-1] + e.w;
                        debug(e.v+":"+distans[e.v  -1]);
                    }
                    visited.add(e);
                }
            }
        }
        for(int i : distans){
            System.out.println(i%2);
        }
    }

    private static void setSet(HashMap<Integer,List<Edge>> set,Edge e, int i){
        List<Edge> list = set.get(i);
        if(list == null){
            list = new ArrayList<>();
        }
        list.add(e);
        set.put(i, list);
    }

}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


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

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

    static class E1Or2 {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            DSet d = new DSet(n);
            for (int i = 0; i < m; i++) {
                d.union(in.nextInt(), in.nextInt());
                int temp = in.nextInt();
            }
            out.println(d.getClusters());
        }

    }

    static class DSet {
        int parent[];
        int rank[];
        int size;

        DSet(int n) {
            parent = new int[n + 1];
            rank = new int[n + 1];
            size = n;
            for (int i = 0; i <= n; i++) {
                this.parent[i] = i;
            }
        }

        public int find(int i) {
            if (parent[i] == i) return i;
            else {
                int result = find(parent[i]);
                parent[i] = result;
                return result;
            }
        }

        public int getClusters() {
            return size;
        }

        public void union(int i, int j) {
            int ipar = this.find(i);
            int jpar = this.find(j);
            if (ipar == jpar) {
                return;
            }
            int irank = this.rank[ipar];
            int jrank = this.rank[jpar];
            if (irank < jrank) {
                this.parent[ipar] = jpar;
            } else if (jrank < irank) {
                this.parent[jpar] = ipar;
            } else {
                this.parent[ipar] = jpar;
                this.rank[jpar]++;
            }
            size--;
        }

    }

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

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

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

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

    }
}

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
    //SOLUTION BEGIN
    //This code is not meant for understanding, proceed with caution
    void pre() throws Exception{}
    void solve(int TC) throws Exception{
        int n = ni(), ans = 0;
        int[] cnt = new int[4];
        for(int i = 0; i< n; i++){
            String s= n();
            for(int j = 0; j< s.length()-1; j++)if(s.charAt(j)=='A' && s.charAt(j+1)=='B')ans++;
            int ty = 0;
            if(s.charAt(0)=='B')ty+=1;
            if(s.charAt(s.length()-1)=='A')ty+=2;
            cnt[ty]++;
        }
        if(cnt[2]+cnt[3]>0){
            if(cnt[2]>0)ans+=cnt[3]+Math.min(cnt[1], cnt[2]);
            else ans+= cnt[3]-1+(cnt[1]>0?1:0);
        }
        pn(ans);
    }
    class Pair{
        int ty;
        String s;
        public Pair(String S){
            s = S;
            if(s.charAt(0)=='B')ty+=1;
            if(s.charAt(s.length()-1)=='A')ty+=2;

        }
    }
    //SOLUTION END
    void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
    long mod = (long)998244353, IINF = (long)1e18;
    final int INF = (int)1e9, MX = (int)1e5+1;
    DecimalFormat df = new DecimalFormat("0.00000000000");
    double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8;
    static boolean multipleTC = false, memory = false;
    FastReader in;PrintWriter out;
    void run() throws Exception{
        in = new FastReader();
        out = new PrintWriter(System.out);
        int T = (multipleTC)?ni():1;
        pre();for(int t = 1; t<= T; t++)solve(t);
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws Exception{
        if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
        else new Main().run();
    }
    long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
    int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
    int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
    void p(Object o){out.print(o);}
    void pn(Object o){out.println(o);}
    void pni(Object o){out.println(o);out.flush();}
    String n()throws Exception{return in.next();}
    String nln()throws Exception{return in.nextLine();}
    int ni()throws Exception{return Integer.parseInt(in.next());}
    long nl()throws Exception{return Long.parseLong(in.next());}
    double nd()throws Exception{return Double.parseDouble(in.next());}

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

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

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

        String nextLine() throws Exception{
            String str = "";
            try{
                str = br.readLine();
            }catch (IOException e){
                throw new Exception(e.toString());
            }
            return str;
        }
    }
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


import java.util.*;

public class Main {

    void run() {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        LinkedList<Integer> as = new LinkedList<>(), bs = new LinkedList<>();
        HashSet<Integer> ain = new HashSet<>();

        for (int i = 0; i < n; i++) {
            String s = sc.next();
            for (int j = s.length() - 2; j > 0; j--) {
                if (s.charAt(j - 1) == 'A' && s.charAt(j) == 'B') ans++;
            }
            if (s.charAt(0) == 'B') {
                if (s.charAt(s.length() - 1) == 'A') bs.addFirst(i);
                else bs.addLast(i);
            }
            if (s.charAt(s.length() - 1) == 'A') {
                if (s.charAt(0) == 'B') {
                    as.addLast(i);
                } else {
                    as.addFirst(i);
                }
                ain.add(i);
            }
        }
//        debug(ans, as, bs);

        boolean[] used = new boolean[n];
        if (!as.isEmpty()) {
            int i = as.removeFirst();
            while (!bs.isEmpty()) {
                if (ain.contains(i)) {
                    // nothing
                } else {
                    used[i] = true;
                    while (!as.isEmpty() && used[i]) i = as.removeFirst();
                    if (used[i]) break;
                }
                used[i] = true;
                while (!bs.isEmpty()) {
                    int j = bs.remove();
                    if (used[j]) continue;
//                debug(i, j);
                    i = j;
                    ans++;
                    break;
                }
            }
        }
        System.out.println(ans);
    }

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

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


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

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

class Mod{
    static final long MOD = 1000_000_007;
    static final long[] fact = makeFactorialArray(1000000);
    static final long[] factInv = makeInversedArray(fact);

    public static long add(long a, long b){
        long tmp = (a+b)%MOD;
        return tmp>=0 ? tmp : tmp+MOD;
    }
    public static long sub(long a, long b){
        return add(a,-b);
    }
    public static long mult(long a, long b){
        long tmp = (a*b)%MOD;
        return tmp>=0 ? tmp : tmp+MOD;
    }
    public static long power(long a, long x){ //calculate a^x
        if(x<0)return 0;
        if(x==0)return 1;
        if(x%2==0) {
            long half = power(a,x/2);
            return mult(half,half);
        }
        return (a*power(a,x-1)) % MOD;
    }
    public static long inverse(long a){
        return power(a,MOD-2);
    }
    public static long div(long a, long b){
        return mult(a, inverse(b));
    }
    public static long[] makeFactorialArray(int size){
        long[] array = new long[size];
        array[0]=1;
        for(int i=1;i<size;i++){
            array[i]=mult(array[i-1],i);
        }
        return array;
    }
    public static long[] makeInversedArray(long[] original){
        long[] array = new long[original.length];
        for(int i=0;i<original.length;i++){
            array[i] = inverse(original[i]);
        }
        return array;
    }
    public static long combination(int n, int r){
        if(n<0 || r<0 || n<r) return 0;
        return mult(fact[n], mult(factInv[r],factInv[n-r]));
    }
    public static long gcd(long a, long b){
        if(a<b) return gcd(b,a);
        if(b==0) return a;
        if(a%b==0) return b;
        return gcd(b,a%b);
    }
    public static long lcm(long a, long b){
        return (a/gcd(a,b))*b;
    }

}

class Counter<T> extends HashMap<T,Long>{
    long def;
    public Counter(long d){
        super();def=d;
    }
    public Long get(Object elm){
        return getOrDefault(elm,def);
    }
    public void add(T elm, long amount){
        if(!this.containsKey(elm)) put(elm, Mod.add(def,amount));
        else replace(elm, Mod.add(get(elm),amount));
    }
    public void addOne(T elm){
        add(elm, 1L);
    }

}
public class Main {
    static int countAB(String s){
        return (s.length() - s.replaceAll("AB", "").length()) / 2;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        long[] A = new long[N];
        for(int n=0; n<N; n++) A[n]=sc.nextLong();

        long[] X = new long[N+1];
        for(int n=0; n<N; n++) X[n+1]=X[n]^A[n];

        if(X[N]==0){
            Counter<Long> counter0 = new Counter<>(1);
            Counter<Long> counterX = new Counter<>(0);
            for(int n=1; n<N; n++){
                if(X[n]==0){
                    for(long x: counterX.keySet()) counter0.add(x, counterX.get(x));
                }
                else{
                    counterX.add(X[n], counter0.get(X[n]));
                }
            }

            long zeroOnly = 1L;
            for(int n=1; n<N; n++) if(X[n]==0) zeroOnly = Mod.mult(zeroOnly, 2);

            long ans = 0;
            for(long e: counterX.keySet()) ans = Mod.add(ans, counterX.get(e));
            ans = Mod.add(ans, zeroOnly);
            System.out.println(ans);

        }else{
            int endZero = 1, endX = 0;
            for(int n=1; n<N; n++){
                if(X[n]==0) endZero += endX;
                if(X[n]==X[N]) endX += endZero;
            }
            System.out.println(endZero);
        }

    }
}

Score : 800 points

Problem Statement

The beauty of a sequence a of length n is defined as a_1 \oplus \cdots \oplus a_n, where \oplus denotes the bitwise exclusive or (XOR).

You are given a sequence A of length N.
Snuke will insert zero or more partitions in A to divide it into some number of non-empty contiguous subsequences.

There are 2^{N-1} possible ways to insert partitions.
How many of them divide A into sequences whose beauties are all equal? Find this count modulo 10^{9}+7.

Constraints

All values in input are integers.

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

0 \leq A_i < 2^{20}

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

3

Four ways of dividing A shown below satisfy the condition. The condition is not satisfied only if A is divided into (1),(2),(3).

(1,2,3)

(1),(2,3)

(1,2),(3)

Sample Input 2

3
1 2 2

Sample Output 2

1

Sample Input 3

32
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Sample Output 3

147483634

Find the count modulo 10^{9}+7.

Sample Input 4

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

Sample Output 4

292


import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@SuppressWarnings("unused")
public class Main {

	//final boolean isDebug = true;
	final boolean isDebug = false;
	String fileName = "input.txt";
	FastScanner sc;
	PrintWriter out;
	final int MOD = (int)1e9+7;
	final int INF = Integer.MAX_VALUE / 2;

	void solve() throws Exception{
		int H = sc.nextInt();
		int W = sc.nextInt();
		int N = sc.nextInt();
		int sx = sc.nextInt(), sy = sc.nextInt();
		String T = sc.next();
		String A = sc.next();
		String t = "LRUD";
		String a = "RLDU";
		int[] dyt = {0, 0, -1, 1};
		int[] dya = {0, 0, 1, -1};
		int[] dxt = {-1, 1, 0, 0};
		int[] dxa = {1, -1, 0, 0};

		for(int i = 0; i < 4; i++){
			int x = sx, y = sy;
			for(int j = 0; j < N; j++){
				if(T.charAt(j) == t.charAt(i)){
					x += dxt[i];
					y += dyt[i];
				}
				if(x <= 0 || x > W || y <= 0 || y > H){
					System.out.println("NO");
					return;
				}
				if(A.charAt(j) == a.charAt(i)){
					if(x + dxa[i] >= 1 && x + dxa[i] <= W && y + dya[i] >= 0 && y + dya[i] <= H){
						x += dxa[i];
						y += dya[i];
					}
				}
			}
		}
		System.out.println("YES");
	}

	/* end solve */

	/* main */
	public static void main(String[] args) throws Exception {
		new Main().m();
	}

	void m() throws Exception {
		long S = System.currentTimeMillis();
		sc = (isDebug) ? new FastScanner(new FileInputStream(fileName)) : new FastScanner(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		if(isDebug){
			System.out.println("---Debug---");
			System.out.printf("%8d ms", (G-S));
		}
	}
	/* end main */
}
/* end Main */

class FastScanner {
    private InputStream in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public FastScanner(InputStream in) {
		this.in = in;
	}
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() {
    	if (hasNextByte()) return buffer[ptr++];
    	else return -1;
    }
    private static boolean isPrintableChar(int c){
    	return 33 <= c && c <= 126;
    }
    public boolean hasNext() {
    	while(hasNextByte() && !isPrintableChar(buffer[ptr]))
    		ptr++; return hasNextByte();
    }
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public String nextLine() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(b != 10) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() {
    	return Double.parseDouble(next());
    }
}

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

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

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		try(Scanner sc = new Scanner(System.in)){

			int a = sc.nextInt();
			int b = sc.nextInt();
			int t = sc.nextInt();

			System.out.println(t / a * b);
		}

	}
}

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<Integer> valueList = new ArrayList<>();
        for (int i=0; i<n; i++){
            valueList.add(sc.nextInt());
        }
        List<Integer> costList = new ArrayList<>();
        for (int i=0; i<n; i++){
            costList.add(sc.nextInt());
        }

        int totalBenefit = 0;

        for (int i=0; i<n; i++){
            int benefit = valueList.get(i) - costList.get(i);
            if (benefit > 0){
                totalBenefit += benefit;
            }
        }

        System.out.println(totalBenefit);
    }
}

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


import java.util.*;

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

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int[] v;
        int[] c;

        v = new int[49];
        c = new int[49];
        N -=1;
        for(int i=0;i<=N;i++){
            v[i] = sc.nextInt();
        }
        for(int j=0;j<=N;j++){
            c[j] = sc.nextInt();
        }

        int X = v[0]+v[N];
        int Y = c[0]+c[N];

        int xy = X -Y;

        if(xy>0){
            System.out.println(xy);
        }else{
            System.out.println(0);
        }

    }
}


import java.util.Scanner;

public class Main {
		public static void main(String[] args) {
			String strV, strC;
			int N, result = 0;
			int[] V = new int[20];
			int[] C = new int[20];

			Scanner scN = new Scanner(System.in);
			N = Integer.parseInt(scN.nextLine());
			strV = scN.nextLine();
			strC = scN.nextLine();

			System.out.println(strC);

			for (int i = 0; i < N; i++) {
				V[i] = Integer.parseInt(strV.split(" ")[i]);
				C[i] = Integer.parseInt(strC.split(" ")[i]);
			}

			for (int i = 0; i < N; i++) {
				if (V[i] - C[i] > 0) {
					result += V[i] - C[i];
				}
			}

			System.out.print(result);

			scN.close();
		}
}


import java.io.IOException;
import java.util.Scanner;

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

        if((a < c && c < b)||(b < c && c < a)) System.out.println("Yes");
        else System.out.println("No");

    }

}

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // int times = Integer.parseInt(sc.nextLine());
        // int bit = 0;

        int x1 = Integer.parseInt(sc.nextLine());
        String s = sc.nextLine();

        int t1 = s.indexOf("#");

        int cnt = 0;

        while (true) {
            if (t1 < 0)
                break;
            if (t1 + 1 >= x1)
                break;
            if (s.charAt(t1 + 1) == '.') {
                cnt++;
            }
            if (t1 + 1 >= x1) {
                break;
            } else {
                t1 = s.indexOf("#", t1 + 1);
            }
            if (t1 >= x1 - 1) {
                break;
            } else if (t1 < 0) {
                break;
            }

        }

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


import java.util.*;

public class Main {
  public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int num1 = sc.nextInt();
          int num2 = sc.nextInt();
          int sum = 0;
          for(int i = 0; i < 2; i++){
            if(num1 < num2){
              sum += num2;
              num2--;
            } else {
              sum += num1;
              num1--;
            }
          }
          System.out.println(sum);
      }
    }

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] h = new int[n];
    int max = 0;
    int count = 0;
    for(int i = 0;i<n;i++){
      h[i] = sc.nextInt();
      if(max <= h[i]){
        max = h[i];
        count++;
      }
    }
    System.out.println(count);
  }
}

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


import java.util.Scanner;

class Main {
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int N = sc.nextInt();
       	int A[] = new int[N];
    	int ans=0;
    	boolean check = false;
       	for(int i =0;i<N;i++){
       		A[i] = sc.nextInt();
       	}
    	for(int i =0;i<N;i++){
           check = true;
    		for(int j=0;j<i;j++){

    			if(A[j]>A[i]){
    				check = false;

    			}

    			}
    		if(check = true ){
    			ans ++;
    		}

    	}
    	System.out.println(ans);

}

}


import java.util.Scanner;

public class Main {

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

		int n = sc.nextInt();
		int [] h = new int[n];
		for(int i = 0;i < n;i++){
			h[i] = sc.nextInt();
		}
		int cnt = 1;
		int max = h[0];
		for(int i = 0;i < n-1;i++){
			if(max < h[i+1]){
				cnt++;
				max = h[i+1];
			}
		}
		System.out.println(cnt);
	}
}


import java.util.Scanner;

public class Main {

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

		int n=Integer.parseInt(sc.next());
		int h[]=new int[100];
		int sum=0;
		int j;

		for(int i=0;i<n;i++){
			h[i]=Integer.parseInt(sc.next());
			for(j=i;j>0;j--){
				if(i!=0&&h[i]<h[j]){
					break;
				}
			}
			if(j==0)sum+=1;

		}
		System.out.println(sum);
	}

}


import java.util.*;

class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    long l = Long.parseLong(s, 2);

    long ans1 = 0;
    long ans2 = 0;
    for(long i = 0; i < s.length(); i++) {
      if (i%2 == 1) {
        if ((1 & l>>i) == 0) {
          ans1++;
        }
      } else {
        if ((1 & l>>i) == 1) {
          ans1++;
        }
      }

      if (i%2 == 0) {
        if ((1 & l>>i) == 0) {
          ans2++;
        }
      } else {
        if ((1 & l>>i) == 1) {
          ans2++;
        }
      }

    }
    System.out.println(Math.min(ans1, ans2));
  }
}

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

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

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        String s = sc.next();
        List<Integer> kList = new ArrayList<>();
        List<Integer> oneList = new ArrayList<>();

        boolean f = true;
        int z = 0;
        int one = 0;
        boolean firstoneFlag = false;
        for(int i = 0; i < n; i++){
            z++;
            char c = s.charAt(i);
            if(i == 0 && c == '1'){
                firstoneFlag = true;
            }
            if(c == '1'){
                if(f){
                    one++;
                }else{
                    f = true;
                    kList.add(z);
                    if(firstoneFlag){
                        firstoneFlag = false;
                    }else{
                        oneList.add(one);
                    }
                    one = 1;
                }
            }else{
                f = false;
            }
        }

        if(f){
            oneList.add(one);
        }else{
            kList.add(z);
            oneList.add(0);
        }

        long max = 0;
        int index = -1;
        for(int i = k - 1; i < kList.size(); i++){
            long tmp = 0;
            if(index == -1){
                tmp = kList.get(i) + oneList.get(i);
            }else{
                tmp = kList.get(i) + oneList.get(i) - kList.get(index);
            }
            if(max < tmp){
                max = tmp;
            }
            index++;
        }

        if(max == 0){
            max = n;
        }

        System.out.println(max);

    }
}

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


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

/* abhi2601 */

public class Main implements Runnable{

    final static long mod = (long)1e9 + 7;

    class Pair{
        int l,r;
        Pair(int l,int r){
            this.l=l;
            this.r=r;
        }
    }
    class Comp implements Comparator<Pair>{
        public int compare(Pair p1, Pair p2){
            if(p1.l<p2.l) return -1;
            else if(p1.l>p2.l) return 1;
            else{
                if(p1.r<p2.r) return -1;
                else if(p1.r>p2.r) return 1;
                else return 0;
            }
        }
    }
    public void run(){
        InputReader sc = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);
        int n=sc.nextInt();
        int k=sc.nextInt();
        String s=sc.next();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<n;i++){
            if(s.charAt(i)=='0') sb.append('1');
            else sb.append('0');
        }
        String s1=sb.toString();
        int k1=k-1;
        Queue<Integer>q=new LinkedList<>();
        Queue<Integer>q1=new LinkedList<>();
        int c=0,t=0,ans=0,p=-1;
        for(int i=0;i<n;i++){
            if(s.charAt(i)=='0'){
                c++;
                if(c==1){
                    if(t>k){
                        p=q.poll();
                        t--;
                    }
                    ans=Math.max(ans,i-p-1);
                }
            }
            else{
                if(c!=0){
                    t++;
                    q.add(i-1);
                    c=0;
                }
                if(i==n-1){
                    if(t>k){
                        p=q.poll();
                        t--;
                    }
                    ans=Math.max(ans,i-p);
                }
            }
        }
        int c1=0,t1=0,ans1=0,p1=-1;
        for(int i=0;i<n;i++){
            if(s1.charAt(i)=='0'){
                c1++;
                if(c1==1){
                    if(t1>k1){
                        p1=q1.poll();
                        t1--;
                    }
                    ans1=Math.max(ans1,i-p1-1);
                }
            }
            else{
                if(c1!=0){
                    t1++;
                    q1.add(i-1);
                    c1=0;
                }
                if(i==n-1){
                    if(t1>k1){
                        p1=q1.poll();
                        t1--;
                    }
                    ans1=Math.max(ans1,i-p1);
                }
            }
        }
        w.println(Math.max(ans,ans1));
        w.close();
    }
    //static PrintWriter w;
    /*File in=new File("input.txt");
        File out=new File("output.txt");
        Scanner sc= null;
        try {
            sc = new Scanner(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            w=new PrintWriter(out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
    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 read()
        {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine()
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

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

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

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

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

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

    public static void main(String args[]) throws Exception
    {
        new Thread(null, new Main(),"q1",1<<26).start();
    }
}


import java.util.*;

public class Main{

	public static void main(String[] args){

		Scanner sc =new Scanner(System.in);
		int[] dish = new int[5];
		for(int i=0;i<5;i++){
			dish[i] = sc.nextInt();
		}

		int[] point = new int[5];
		int[] ones_place=new int[5];
		for(int i=0;i<5;i++){
			if(dish[i] >=100){
				ones_place[i] = dish[i]/100;
				if(ones_place[i] == 0)
					ones_place[i] = 10;

					point[i] = dish[i]+10-ones_place[i];

			}else if(dish[i]>=10){
					ones_place[i]=dish[i]/10;
					if(ones_place[i] == 0)
					ones_place[i] = 10;

					point[i] = dish[i]+10-ones_place[i];
				}else{
					ones_place[i]=dish[i];
					if(ones_place[i] == 0)
					ones_place[i] = 10;

					point[i] = dish[i]+10-ones_place[i];
				}
		}

		Arrays.sort(ones_place);
		int time=0;

		for(int i=0;i<point.length;i++){
			time=time+point[i];
		}

		System.out.println(time-10+ones_place[0]);
	}
}

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


import java.util.*;
import java.math.BigDecimal;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		BigDecimal N = nextBigDecimal(sc);
		BigDecimal minMovePeople = nextBigDecimal(sc);
		for (int i = 1; i < 5; i++) {
		    BigDecimal current = nextBigDecimal(sc);
		    if (current.compareTo(minMovePeople) < 0) {
		        minMovePeople = current;
		    }
		}
		BigDecimal result = N.divide(minMovePeople);
		BigDecimal result2 = result.setScale(0, java.math.RoundingMode.DOWN);
		System.out.println(result2.add(new BigDecimal("5")));
	}

	public static BigDecimal nextBigDecimal(Scanner sc) {
	    return new BigDecimal(sc.next());
	}
}

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


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

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

    static class DCake123 {
        static int x;
        static int y;
        static int z;
        static int k;
        static Long[] a;
        static Long[] b;
        static Long[] c;

        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            x = sc.nextInt();
            y = sc.nextInt();
            z = sc.nextInt();
            k = sc.nextInt();
            a = new Long[x];
            b = new Long[y];
            c = new Long[z];
            for (int i = 0; i < x; i++) {
                a[i] = sc.nextLong();
            }
            for (int i = 0; i < y; i++) {
                b[i] = sc.nextLong();
            }
            for (int i = 0; i < z; i++) {
                c[i] = sc.nextLong();
            }
            Arrays.sort(a, Collections.reverseOrder());
            Arrays.sort(b, Collections.reverseOrder());
            Arrays.sort(c, Collections.reverseOrder());
            long bord = 0;
            long l = 1;
            long r = (long) 1e11;
            while (r - l >= 0) {
                long mid = (l + r) / 2;
                if (check(mid)) {
                    bord = mid;
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
            ArrayList<Long> ans = new ArrayList<>();
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    for (int t = 0; t < z; t++) {
                        if (a[i] + b[j] + c[t] >= bord) {
                            ans.add(a[i] + b[j] + c[t]);
                        } else {
                            break;
                        }
                    }
                }
            }
            Collections.sort(ans, Collections.reverseOrder());
            for (int i = 0; i < k; i++) {
                out.println(ans.get(i));
            }
        }

        static boolean check(long mid) {
            int nb = 0;
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    if (a[i] + b[j] >= mid) {
                        nb += z;
                        if (nb >= k) return true;
                    } else {
                        for (int l = 0; l < z; l++) {
                            if (a[i] + b[j] + c[l] >= mid) {
                                nb++;
                            } else {
                                break;
                            }
                            if (nb >= k) return true;
                        }
                    }
                }
            }
            return false;
        }

    }

    static class inputClass {
        BufferedReader br;
        StringTokenizer st;

        public inputClass(InputStream in) {

            br = new BufferedReader(new InputStreamReader(in));
        }

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

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

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

    }
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

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


import java.util.*;

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

        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

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

Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


import java.util.*;

public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    //int N = sc.nextInt();
    //int[] count = new int[N];
    String str = sc.next();
    int max = 0;
    int count = 0;

    for(int i=0; i < str.length(); i++){
        if(str.charAt(i) == 'A' || str.charAt(i) == 'C' || str.charAt(i) == 'G' || str.charAt(i) == 'T'){
            count++;
        }else{
            count = 0;
        }
        if(max < count){
            max = count;
        }
    }
    //if(str[0].equals("H"));
    System.out.println(max);
  }
}

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


import java.util.*;

public class Main {

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

        int max = 0;
        int tmp = 0;
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (ch == 'A' || ch == 'C' || ch == 'G' || ch == 'T') ++tmp;
            else tmp = 0;
            if (tmp > max) max = tmp;
        }

        System.out.println(max);
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		String S = sc.next();
		List<Integer> list = new ArrayList<Integer>();
		list.add(0);
		for (int i = 0; i < S.length(); i++) {
			char t = S.charAt(i);
			if (t != 'A' && t !='C' && t != 'G' && t != 'T') {
				list.add(i+1);
			}
		}
		list.add(S.length()+1);
		int ans = 0;
		for (int i = 0; i < list.size() -1; i++) {
			int t = list.get(i+1) - list.get(i) - 1;
			if (t > ans) {
				ans = t;
			}
		}
		System.out.println(ans);
	}
}

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

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

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

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

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

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

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

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

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


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Closeable;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.io.InputStream;

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

    static class BATCoder {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            String s = in.next();
            List<String> cands = new ArrayList<>();
            cands.add("");
            for (int i = 0; i < s.length(); i++) {
                for (int j = i + 1; j <= s.length(); j++) {
                    String part = s.substring(i, j);
                    if (part.matches("[ACGT]+")) {
                        System.err.println(part);
                        cands.add(part);
                    }
                }
            }
            cands.sort(Comparator.comparing(String::length).reversed());
            out.println(cands.get(0).length());
        }

    }

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

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

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

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

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

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

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

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

    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int q = sc.nextInt();
		char[] s = sc.next().toCharArray();
		int[] a = new int[n];
		for (int i = 1; i < n; i++) {
			if(s[i-1]=='A'&&s[i]=='C') a[i] += 1;
			a[i] += a[i-1];
		}
		int l = 0, r = 0; String[] lr = new String[2];
		sc.nextLine();
		for (int i = 0; i < q; i++) {
			lr = sc.nextLine().split(" ");
			l = Integer.parseInt(lr[0])-1;
			r = Integer.parseInt(lr[1])-1;
			if(l == 0) {
				System.out.println(a[r]);
			}else {
				n = (s[l]=='C'&&s[l-1]=='A')?1:0;
				System.out.println(a[r]-a[l-1]-n);
			}
		}
		sc.close();
	}
}

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		sc.nextInt();
		int q = sc.nextInt();
		String s = sc.next();
		AC2 ac = new AC2(s);

		for (int i = 0; i < q; i++) {
			int l = sc.nextInt();
			int r = sc.nextInt();
			int ans = ac.getAC(l, r);
			System.out.println(ans);
		}

	}

}

class AC2 {
	String s;
	ArrayList<Integer> acList = new ArrayList<>();
	AC2(String s) {
		this.s = s;
		boolean a = false;
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if (a) {
				if (ch == 'C') {
					acList.add(i);
					a = false;
					continue;
				}
			}
			a = (ch == 'A') ? true : false;
		}
	}
	int getAC(int l, int r) {
		int ac = 0;
		for (int acIndex : acList) {
			if (acIndex > r - 1) {
				break;
			}
			if (acIndex >= l) {
				ac++;
			}
		}
		return ac;
	}
}


import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int length = sc.nextInt();
        int n = sc.nextInt();
        sc.nextLine();
        String q = sc.nextLine();
        char[] qc = q.toCharArray();
        int data[] = new int[length+1];
        for(int i = 2;i<=length;i++){
            if(qc[i-2] == 'A' && qc[i-1] == 'C'){
                data[i] = data[i-1] + 1;
            }else{
                data[i] = data[i-1];
            }
        }
        int tmp = 0;
        for(int i = 0;i<n;i++){
            tmp = sc.nextInt();
            System.out.println(data[sc.nextInt()] - data[tmp]);
            sc.nextLine();
        }
    }
}


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

public class Main {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try (Scanner sc = new Scanner(br)) {
			int len = sc.nextInt();
			int numOfQuestion = sc.nextInt();
			String str = sc.next();
			question(str, numOfQuestion, sc);
		}
	}

	private static void question(String str, int numOfQuestion, Scanner sc) {
		int[] counts = countAC(str);
		for (int i = 1; i <= numOfQuestion; i++) {
			int l = sc.nextInt() - 1;
			int r = sc.nextInt() - 1;
			System.out.println(counts[r - 1]  - (l > 0 ? counts [l - 1] : 0));
		}
	}

	// 0〜i番目の部分文字列がACの場合の数
	private static int[] countAC(String str) {
		int[] counts = new int[str.length() - 1];
		char[] chars = str.toCharArray();
		int len = chars.length;
		int count = 0;
		for (int i = 0; i < len - 1; i++) {
			if (chars[i] == 'A' && chars[i + 1] == 'C') {
				count++;
			}
			counts[i] = count;
		}
		return counts;
	}
}