import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Queue;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.LinkedList;
import java.io.InputStream;

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

    static class APondSkater {
        public void solve(int testNumber, Scanner sc, PrintWriter pw) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            int k = sc.nextInt();
            int[][] grid = new int[n][m];
            int[][] dist = new int[n][m];
            for (int[] x : dist) Arrays.fill(x, 1000000);
            int[] dx = {-1, 0, 1, 0};
            int[] dy = {0, -1, 0, 1};
            int x1 = sc.nextInt() - 1;
            int y1 = sc.nextInt() - 1;
            int x2 = sc.nextInt() - 1;
            int y2 = sc.nextInt() - 1;
            for (int i = 0; i < n; i++) {
                char[] tmp = sc.nextLine().toCharArray();
                for (int j = 0; j < m; j++) {
                    grid[i][j] = (tmp[j] == '@' ? 1 : 0);
                }
            }
            boolean[][] vis = new boolean[n][m];
            Queue<pair> q = new LinkedList<>();
            q.add(new pair(x1, y1));
            dist[x1][y1] = 0;
            vis[x1][y1] = true;
            int ans = Integer.MAX_VALUE;
            while (q.size() > 0) {
                pair cur = q.poll();
                if (cur.a == x2 && cur.b == y2) {
                    ans = Math.min(ans, dist[x2][y2]);
                    break;
                }
                for (int i = 0; i < 4; i++) {
                    for (int c = 1; c <= k; c++) {
//                    if(cur.a ==0&&cur.b==3){
//                        pw.println(cur.a+c*dx[i]+" "+(cur.b+c*dy[i]));
//                    }
                        if (valid(cur.a + c * dx[i], cur.b + c * dy[i], n, m) && grid[cur.a + c * dx[i]][cur.b + c * dy[i]] == 0) {
                            if (!vis[cur.a + c * dx[i]][cur.b + c * dy[i]])
                                if (1 + dist[cur.a][cur.b] < dist[cur.a + c * dx[i]][cur.b + c * dy[i]]) {
                                    vis[cur.a + c * dx[i]][cur.b + c * dy[i]] = true;
                                    dist[cur.a + c * dx[i]][cur.b + c * dy[i]] = 1 + dist[cur.a][cur.b];
                                    q.add(new pair(cur.a + c * dx[i], cur.b + c * dy[i]));
                                } else break;
                        } else break;
                    }
                }
            }
//        for(int []x:dist){
//            for(int y :x){
//                pw.print((y==1000000?-1:y)+" ");
//            }pw.println();
//        }
            pw.println(ans == Integer.MAX_VALUE ? -1 : ans);

        }

        boolean valid(int i, int j, int n, int m) {
            if (i < 0) return false;
            if (i >= n) return false;
            if (j < 0) return false;
            if (j >= m) return false;
            return true;
        }

        public class pair implements Comparable<pair> {
            int a;
            int b;

            public pair(int a, int b) {
                this.a = a;
                this.b = b;
            }

            public int compareTo(pair pair) {
                return a - pair.a == 0 ? b - pair.b : a - pair.a;
            }

        }

    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(FileReader r) {
            br = new BufferedReader(r);
        }

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

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

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

        public String nextLine() {
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


import java.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax
    static final int INF = 1_000_000_000; // 10^9
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		long a = saori.saorihayami();
		long v = saori.saorihayami();
		long b = saori.saorihayami();
		long w = saori.saorihayami();
		long t = saori.saorihayami();
		if(a < b){
			if(a+v*t >= b+w*t){
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		} else {
			if(a+v*t <= b+w*t){
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}

		saori.close();
    }
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() {
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) {
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() {
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }

}

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

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

-10^9 \leq A,B \leq 10^9

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO

Submitted source-code file size, in bytes.

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

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


import java.util.Scanner;
class Main{
  public static void main(String[] args){
    Scanner scn = new Scanner(System.in);
   	int A,B,V,W,T,tmp;
    A = scn.nextInt();
    V = scn.nextInt();
    B = scn.nextInt();
    W = scn.nextInt();
    T = scn.nextInt();
    if (A == B){
      System.out.print("YES");
    }else if (V > W){
      tmp = V-W;
      if (tmp*(T+1)+A >= B){
		System.out.print("YES");
      }else{
        System.out.print("NO");
      }
    }else{
      System.out.print("NO");
    }
  }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double A = sc.nextDouble();
        double V = sc.nextDouble();
        double B = sc.nextDouble();
        double W = sc.nextDouble();
        double T = sc.nextDouble();

        for (int i = 1; i <= T; i++) {
            if (A == B) {
                System.out.println("YES");
                return;
            }
            if (A < B) {
                A = A + V;
                B = B + W;
            } else if (A > B) {
                A = A;
                B = B + W * i;
            }
        }
        System.out.println("NO");
    }
}


import java.util.*;
import java.io.*;
public class Main{
   public static void main(String[] main) throws Exception{
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = new StringTokenizer(br.readLine());
      PrintWriter out = new PrintWriter(System.out);
      int n = Integer.parseInt(st.nextToken());
      int k = Integer.parseInt(st.nextToken());
      st = new StringTokenizer(br.readLine());
      int[] a = new int[n];
      for(int i = 0; i < n; i++)
    	  a[i] = Integer.parseInt(st.nextToken());
      StringJoiner sj = new StringJoiner(" ");
      if(k > Math.log(n)+1) {
    	  for(int i = 0; i < n; i++)
    		  sj.add(Integer.toString(n));
      }
      else {
    	  for(int i = 0; i < k; i++) {
    		  int[] b = new int[n];
    		  for(int j = 0; j < n; j++) {
    			  b[Math.max(0,j - a[j])]++;
    			  if(j + a[j] < n-1)
    				  b[j + a[j]+1]--;
    		  }
    		  for(int j = 1; j < n; j++) {
    			  b[j] += b[j-1];
    		  }
    		  a = b;
    	  }
    	  for(int i = 0; i < n; i++)
    		  sj.add(Integer.toString(a[i]));
      }
      out.println(sj);
      out.close();
   }
}

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

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

1 \leq K \leq 2 \times 10^5

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


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

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
      int A,B;
      String an = scan.nextLine();
      String atai[] = an.split(" ",0);
      A = Integer.parseInt(atai[0]);
      B = Integer.parseInt(atai[1]);
       //System.out.println(N);
      cal(A,B);
        scan.close();
    }

  public static void cal(int a,int b){
   int s = 0;
    s = a*b;
    System.out.println(s);
    return;
  }
}

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        Map<Long, Integer> primeList = primeFactorizationAsMap(n);
        if (primeList.size() == 0) {
            System.out.println(0);
        } else {
            int result = primeList.values().stream()
                    .mapToInt(v -> {
                        int count = 0;
                        while (v > 0) {
                            v = v - count - 1;
                            if (v >= 0) {
                                count++;
                            }
                        }
                        return count;
                    })
                    .sum();
            System.out.println(result);
        }
    }

    private static Map<Long, Integer> primeFactorizationAsMap(long num) {
        if (num < 2) {
            return new HashMap<>();
        } else {
            Map<Long, Integer> result = new HashMap<>();
            long temp = num;
            double sqrt = Math.sqrt(num);
            for (int i = 2; i <= sqrt; i++) {
                int count = 0;
                while (temp % i == 0) {
                    count++;
                    temp = temp / i;
                }
                if (count != 0) {
                    result.put((long) i, count);
                }
            }
            if (result.size() == 0) {
                result.put(num, 1);
            }
            return result;
        }
    }
}

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


import java.util.*;

public class Main {

    private static final int MAX = 1000000;
    private static final long[] lp = new long[MAX + 1];
    private static final List<Integer> pr = new ArrayList<>();

    static  {
        for (int i = 2; i <= MAX; ++i) {
            if (lp[i] == 0) {
                lp[i] = i;
                pr.add(i);
            }
            for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i*pr.get(j) <= MAX; ++j) {
                lp[i * pr.get(j)] = pr.get(j);
            }
        }
    }

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

        final Scanner in = new Scanner(System.in);
        long N = in.nextLong();
        final long NN = N;

        int count = 0;

        for (long prime = 2; prime*prime <= NN; ++prime) {
            if (lp[(int) prime] == prime && (N % prime == 0)) {
                int cnt = 0;
                while (N % prime == 0) {
                    cnt++;
                    N = N/prime;
                }
                int k = 0;
                int term = 1;

                while (cnt >= 0) {
                    if (cnt >= term) {
                        k++;
                        cnt -= term;
                        term++;
                    } else {
                        break;
                    }
                }

                count += k;
            }
        }

        System.out.println(count);

    }
}


import java.util.*;
import java.io.*;
import java.util.function.*;
// import lib.util.*;
// import lib.graph.*;
// import lib.io.*;
// import lib.math.*;

public class Main {

    public static void main(String[] args) {
        // FastScanner sc = new FastScanner();
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        char[] t = sc.next().toCharArray();
        char prev = 'x';
        String res = "";
        for (int i = 0; i < t.length; i++) {
            if (t[i] == '?') {
                t[i] = 'D';
                if (i + 1 >= t.length) {
                    out.print(t[i]);
                    break;
                }
                if ((t[i + 1] == '?' || t[i + 1] == 'D') && prev != 'P') {
                    t[i] = 'P';
                }
            }
            prev = t[i];
            out.print(t[i]);
        }
        out.println();
        out.flush();

    }

}

class UnionFindTree {
    int[] root;
    int[] rank;
    int[] size;
    int m;

    public UnionFindTree(int n) {
        this.root = new int[n];
        this.rank = new int[n];
        this.size = new int[n];
        this.m = n;
        for (int i = 0; i < n; i++) {
            root[i] = i;
            size[i] = 1;
        }
    }

    public int find(int x) {
        if (root[x] == x)
            return x;
        else {
            return root[x] = find(root[x]);
        }
    }

    public void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y)
            return;
        if (rank[x] < rank[y]) {
            size[find(y)] = size[find(x)];
            root[x] = y;
        } else {
            size[find(x)] = size[find(y)];
            root[y] = x;
            if (rank[x] == rank[y])
                rank[x]++;
        }
        m--;
    }

    public boolean same(int x, int y) {
        return find(x) == find(y);
    }

    public int size(int i) {
        return this.size[find(i)];
    }
}

class Dijkstra {
    private static int prev[];
    private static long dist[];

    public Dijkstra(AbstractGraph graph, int s) {
        prev = new int[graph.n];
        dist = new long[graph.n];
        Arrays.fill(prev, -1);
        Arrays.fill(dist, Long.MAX_VALUE);
        PriorityQueue<Integer> searching = new PriorityQueue<>((x, y) -> Long.compare(dist[x], dist[y]));
        dist[s] = 0;
        searching.add(s);
        while (searching.size() > 0) {
            int now = searching.poll();
            for (Edge e : graph.getEdges(now)) {
                int next = e.to;
                long c = e.cost;
                if (dist[now] + c < dist[next]) {
                    dist[next] = dist[now] + c;
                    prev[next] = now;
                    searching.add(next);
                }
            }
        }
    }

    public int[] path(int to) {
        ArrayList<Integer> rev = new ArrayList<>();
        for (int now = to; now != -1; now = this.prev[now]) {
            rev.add(now);
        }
        int[] path = new int[rev.size()];
        for (int i = 0; i < path.length; i++) {
            path[i] = rev.get(path.length - i - 1);
        }
        return path;
    }

    public long getDist(int t) {
        return dist[t];
    }
}

class WF {
    private static long[][] dist;

    public WF(AbstractGraph graph) {
        dist = new long[graph.n][graph.n];
        for (int i = 0; i < dist.length; i++) {
            Arrays.fill(dist[i], Integer.MAX_VALUE);
        }
        for (int i = 0; i < graph.n; i++) {
            for (Edge e : graph.getEdges(i)) {
                dist[i][e.to] = e.cost;
            }
            dist[i][i] = 0;
        }
        for (int k = 0; k < graph.n; k++) {
            for (int i = 0; i < graph.n; i++) {
                for (int j = 0; j < graph.n; j++) {
                    if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE) {
                        dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
                    }
                }
            }
        }
    }

    public static long getShortest(int s, int t) {
        return dist[s][t];
    }

    public static long[][] getAllDist() {
        return dist;
    }

    public static boolean isNegativeLoop() {
        for (int i = 0; i < dist.length; i++) {
            if (dist[i][i] < 0) {
                return true;
            }
        }
        return false;
    }
}

class Edge {
    int from, to;
    long cost;

    public Edge(int from, int to, long cost) {
        this.from = from;
        this.to = to;
        this.cost = cost;
    }

    public Edge(int from, int to) {
        this.from = from;
        this.to = to;
        this.cost = 1;
    }

    public Edge reverse() {
        return new Edge(to, from, cost);
    }
}

@SuppressWarnings("unchecked")
abstract class AbstractGraph {
    int n;
    int m;
    ArrayList<Edge>[] edges;

    public AbstractGraph(int n) {
        this.n = n;
        this.m = 0;
        this.edges = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            this.edges[i] = new ArrayList<Edge>();
        }
    }

    public void addEdge(Edge e) {
        this.m++;
        this.edges[e.from].add(e);
    }

    public int getV() {
        return this.n;
    }

    public int getE() {
        return this.m;
    }

    public ArrayList<Edge> getEdges(int v) {
        return this.edges[v];
    }

    abstract public boolean isBipartite();

    public boolean isTree() {
        // require Modifying.
        return false;
    }
}

class Graph extends AbstractGraph {
    int n;
    int m;
    // array of edges which is connect to the node
    ArrayList<Edge>[] edges;

    public Graph(int n) {
        super(n);
    }

    public void addEdge(int from, int to, int cost) {
        Edge e = new Edge(from, to, cost);
        super.addEdge(e);
        super.addEdge(e.reverse());
        this.m++;
    }

    @Override
    public void addEdge(Edge e) {
        this.edges[e.from].add(e);
        this.edges[e.to].add(e.reverse());
        this.m++;
    }

    public int getV(int v) {
        return n;
    }

    public int getE() {
        return m;
    }

    public boolean isBipartite() {
        int[] color = new int[n];
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        HashSet<Integer> visited = new HashSet<>();
        queue.add(0);
        color[0] = 1;
        while (queue.size() > 0) {
            int now = queue.poll();
            visited.add(now);
            for (Edge e : getEdges(now)) {
                if (visited.contains(e.to)) {
                    continue;
                }
                if (color[e.to] == color[now])
                    return false;
                queue.add(e.to);
                if (color[e.to] == 0)
                    color[e.to] = -1 * color[now];
            }
        }
        return true;
    }
}

class DirectedGraph extends AbstractGraph {
    int n;
    int m;
    // array of edges which is connect to the node
    ArrayList<Edge>[] edges;

    public DirectedGraph(int n) {
        super(n);
    }

    public void addEdge(int from, int to, int cost) {
        Edge e = new Edge(from, to, cost);
        super.addEdge(e);
        this.m++;
    }

    @Override
    public void addEdge(Edge e) {
        this.edges[e.from].add(e);
        this.m++;
    }

    public int getV(int v) {
        return this.n;
    }

    public int getE() {
        return this.m;
    }

    public boolean isBipartite() {
        // need to rewrite to work
        return false;
    }

}

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

class MyMath {
    public static long gcm(long a, long b) {

        // if (a < b)
        // return gcm(b, a);

        // if (b == 0 || a % b == 0)
        // return b;

        // return gcm(b, a % b);
        if (a < b) {
            long tmp = a;
            a = b;
            b = tmp;
        }
        long r = -1;
        while (r != 0) {
            r = a % b;
            a = b;
            b = r;
        }
        return a;
    }

    public static long summation(long a, long b) {
        return b * (b + 1) / 2 - a * (a - 1) / 2;
    }

    public static long factorial(long n) {

        if (n <= 1)
            return 1;
        else
            return factorial(n - 1) * n;
    }

    public static long[][] binomialTable(int a, long m) {
        long[][] table = new long[a + 1][a + 1];
        for (int i = 0; i < a + 1; i++) {
            table[0][a] = 0;
            table[i][0] = 1;
            table[i][i] = 1;
        }
        for (int i = 1; i < a + 1; i++) {
            for (int j = 1; j < a + 1; j++) {
                if (i < j)
                    table[i][j] = 0;
                else {
                    table[i][j] = (table[i - 1][j - 1] + table[i - 1][j]) % m;
                }
            }
        }
        return table;
    }

    public static long binomial(int n, int k, long m) {
        long res = 1;
        for (int l = n - k + 1; l <= n; l++) {
            res = (res % m) * (l % m) % m;
        }
        for (int r = 1; r <= k; r++) {
            res = (res % m) * modinv(r, m) % m;
        }
        return res;
    }

    public static long pow(long a, long n, long p) {
        if (n == 0)
            return 1;
        if (n == 1)
            return a % p;
        if (n % 2 == 1)
            return a * pow(a, n - 1, p) % p;
        long tmp = pow(a, n / 2, p) % p;
        return tmp * tmp % p;
    }

    public static long modinv(long a, long p) {
        long b, x, u, q, abs_p, tmp;
        abs_p = Math.abs(p);
        b = p;
        x = 1;
        u = 0;
        while (b > 0) {
            q = a / b;
            tmp = u;
            u = x - q * u;
            x = tmp;
            tmp = b;
            b = a - q * b;
            a = tmp;
        }
        return (x < 0) ? abs_p + x : x;
    }

    public static Long[] eratosthenes(int n) {
        Long[] factor_table = new Long[n];
        for (long i = 1; i <= n; i++) {
            factor_table[(int) (i - 1)] = i;
        }
        for (long i = 1; i <= n; i++) {
            if (factor_table[(int) (i - 1)] == i) {
                int j = 2;
                while (i * j <= n) {
                    factor_table[(int) (i * j - 1)] = i;
                    j++;
                }
            }
        }

        return factor_table;
    }

    public static HashMap<Long, Integer> primeFactorization(long n) {
        HashMap<Long, Integer> primes = new HashMap<>();
        for (long p = 2; p * p <= n; p++) {
            int q = 0;
            while (n % p == 0) {
                n /= p;
                q++;
            }
            if (q > 0)
                primes.put(p, q);
        }
        if (n > 1)
            primes.put(n, 1);
        return primes;
    }

    public static ArrayList<Integer> divisor(int n) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        for (int i = 1; i * i <= n; i++) {
            if (n % i == 0) {
                ret.add(i);
                // n=PQ+0→ PもQも約数. ただし、Q=Pは↑で登録済みなので登録しない
                if (i != n / i)
                    ret.add(n / i);
            }
        }
        return ret;
    }
}

class nextPermutation {
    public static int[] swap(int data[], int left, int right) {

        // Swap the data
        int temp = data[left];
        data[left] = data[right];
        data[right] = temp;

        // Return the updated array
        return data;
    }

    // Function to reverse the sub-array
    // starting from left to the right
    // both inclusive
    public static int[] reverse(int data[], int left, int right) {

        // Reverse the sub-array
        while (left < right) {
            int temp = data[left];
            data[left++] = data[right];
            data[right--] = temp;
        }

        // Return the updated array
        return data;
    }

    // Function to find the next permutation
    // of the given integer array
    public static boolean findNextPermutation(int data[]) {

        // If the given dataset is empty
        // or contains only one element
        // next_permutation is not possible
        if (data.length <= 1)
            return false;

        int last = data.length - 2;

        // find the longest non-increasing suffix
        // and find the pivot
        while (last >= 0) {
            if (data[last] < data[last + 1]) {
                break;
            }
            last--;
        }

        // If there is no increasing pair
        // there is no higher order permutation
        if (last < 0)
            return false;

        int nextGreater = data.length - 1;

        // Find the rightmost successor to the pivot
        for (int i = data.length - 1; i > last; i--) {
            if (data[i] > data[last]) {
                nextGreater = i;
                break;
            }
        }

        // Swap the successor and the pivot
        data = swap(data, nextGreater, last);

        // Reverse the suffix
        data = reverse(data, last + 1, data.length - 1);

        // Return true as the next_permutation is done
        return true;
    }
}

class ArrayUtil {
    private static long INF = 1_000_000_000_0L;

    public static int UpperBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj < array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }

    public static int LowerBound(long[] array, long obj) {
        int l = 0, r = array.length - 1;
        while (r - l >= 0) {
            int c = (l + r) / 2;
            if (obj <= array[c]) {
                r = c - 1;
            } else {
                l = c + 1;
            }
        }
        return l;
    }

    // return the length of array's LIS
    public static int LIS(long[] array) {
        long[] dp = new long[array.length + 1];
        Arrays.fill(dp, INF);
        for (int i = 0; i < array.length; i++) {
            int idx = LowerBound(dp, array[i]);
            dp[idx] = array[i];
        }
        return LowerBound(dp, INF - 1);
    }

    public static int StrictLIS(long[] array) {
        long[] dp = new long[array.length + 1];
        Arrays.fill(dp, INF);
        for (int i = 0; i < array.length; i++) {
            int idx = UpperBound(dp, array[i]);
            dp[idx] = array[i];
        }
        return UpperBound(dp, INF - 1);
    }

    public static void debug(int[][] A) {
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                System.out.print(A[i][j] + " ");
            }
            System.out.println();
        }
    }
}

class BinaryIndexedTree {
    int[] data;
    long[] tree;
    int n;

    public BinaryIndexedTree(int[] data) {
        this.data = data;
        this.n = data.length;
        this.tree = new long[n + 1];
        buildTree();
    }

    public void buildTree() {
        for (int i = 0; i < n; i++) {
            add(i + 1, data[i]);
        }
    }

    public void add(int index, int value) {
        for (int i = index; i <= n; i += i & -i) {
            tree[i] += value;
        }
    }

    public long sum(int from, int to) {
        return sum(to) - sum(from - 1);
    }

    public long sum(int index) {
        int sum = 0;
        for (int i = index; i > 0; i -= i & -i) {
            sum += tree[i];
        }
        return sum;
    }
}

Score : 200 points

Problem Statement

For a string S consisting of the uppercase English letters P and D, let the doctoral and postdoctoral quotient of S be the total number of occurrences of D and PD in S as contiguous substrings. For example, if S = PPDDP, it contains two occurrences of D and one occurrence of PD as contiguous substrings, so the doctoral and postdoctoral quotient of S is 3.

We have a string T consisting of P, D, and ?.

Among the strings that can be obtained by replacing each ? in T with P or D, find one with the maximum possible doctoral and postdoctoral quotient.

Constraints

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

T consists of P, D, and ?.

Input

Input is given from Standard Input in the following format:

T

Output

Print one string with the maximum possible doctoral and postdoctoral quotient among the strings that can be obtained by replacing each ? in T with P or D.
If there are multiple such strings, you may print any of them.

Sample Input 1

PD?D??P

Sample Output 1

PDPDPDP

This string contains three occurrences of D and three occurrences of PD as contiguous substrings, so its doctoral and postdoctoral quotient is 6, which is the maximum doctoral and postdoctoral quotient of a string obtained by replacing each ? in T with P or D.

Sample Input 2

P?P?

Sample Output 2

PDPD


import java.util.*;

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

		String t = sc.next();

		for(int i = 0; i < t.length(); i++) {
			if(t.charAt(i) == '?') {
				System.out.print('D');
			} else {
				System.out.print(t.charAt(i));
			}
		}
		System.out.println("");

	}
}


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

public class Main {

	private static List<Long> getStrings(Scanner sc, int num) {
		List<Long> stringList = new ArrayList<>();
		while(num>0) {
			long n = sc.nextLong();
			stringList.add(n);
			num--;
		}
		return stringList;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		List<Long> treeList = getStrings(sc, n+1);
		long[] treeArray = new long[n+1];
		if (n == 0) {
			if (treeList.get(0) == 1) {
				System.out.println(1);
			} else {
				System.out.println(-1);
			}
			return;
		}
		treeArray[n] = treeList.get(n);
		for (int i = n-1; i >= 0; i--) {
			long max = (long)Math.pow(2.0, i);
			if (treeList.get(i) > max) {
				System.out.println(-1);
				return;
			}
			long tobeRoot = max - treeList.get(i);
			if (tobeRoot <=0) {
				System.out.println(-1);
				return;
			}
			long uppermax = 1;
			if (i != 0) {
				long upper = (long)Math.pow(2.0, i-1) - treeList.get(i-1);
				uppermax = upper*2;
			}
			treeArray[i] = Math.min(Math.min(treeArray[i+1] + treeList.get(i), max), uppermax);
		}
		for (int i = 1; i <= n; i++) {
			treeArray[i] = Math.min(treeArray[i], (treeArray[i-1]-treeList.get(i-1))*2);
		}
		long sum = 0;
		for (int i = 0; i <= n; i++) {
			sum+=treeArray[i];
			// comment out
//			System.out.print(treeArray[i] + ", " + Math.pow(2, i));
//			System.out.println();
		}
		System.out.println(sum);
	}

}

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


public class Main {
    public static void main(String[] args) {
        var arg = Integer.parseInt(args[0]);
        var num = arg % 10;
        String reuslt = null;
        switch (num) {
            case 2:
            case 4:
            case 5:
            case 7:
            case 9:
                reuslt = "hon";
                break;
            case 0:
            case 1:
            case 6:
            case 8:
                reuslt = "pon";
                break;
            case 3:
                reuslt = "bon";
                break;
            default:
                throw new IllegalArgumentException();
        }

        System.out.println(reuslt);
    }
}

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {

		double ans = 0;
		Scanner scan = new Scanner(System.in);
		int minutes_length  = scan.nextInt();
		int hour_length  = scan.nextInt();
		double hour_time  = scan.nextInt();
		double minutes_time  = scan.nextInt();

		double minutes_pi = Math.PI/30*minutes_time;
		double hour_pi = Math.PI/6*(hour_time+ minutes_time/60);
		double theta = Math.PI/30*(5*(hour_time+ minutes_time/60)-minutes_time);
		ans = minutes_length*minutes_length+hour_length*hour_length-2*hour_length*minutes_length*Math.cos(theta);

		System.out.println( Math.sqrt(ans));
	}

}


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String N = sc.next();
    char endChar = N.charAt(N.length() - 1);

    if (endChar == '2' || endChar == '4' || endChar == '5' || endChar == '7' || endChar == '9') {
      System.out.println("hon");
    }
    if (endChar == '0' || endChar == '1' || endChar == '6' || endChar == '8') {
      System.out.println("pon");
    }
    if (endChar == '3') {
      System.out.println("bon");
    }
  }
}


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Main {

    public static void main(String[] args) {

    	FastScanner scan = new FastScanner();

    	int k = scan.nextInt(); String str = scan.next();
    	if(str.length() <= k) System.out.println(str);
    	else {
    		char [] ch = str.toCharArray();
    		str = "";
    		for(int i=0; i<k; i++) str += ch[i];
    		System.out.println(str + "...");
    	}

    }

    static class FastScanner{

    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	StringTokenizer st = new StringTokenizer("");
    	String next() {
    		while(!st.hasMoreTokens())
    			try {
    				st = new StringTokenizer(br.readLine());
    			} catch (IOException e){
    				e.printStackTrace();
    			}
    		return st.nextToken();
    	}

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

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

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

    }

}

Score: 200 points

Problem Statement

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

Constraints

K is an integer between 1 and 100 (inclusive).

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

K
S

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.

We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


package procon01;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws IOException {
//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//		String W	 = in.readLine();
//		int num = Integer.parseInt(W.split(" ")[0]);

		Scanner sc = new Scanner(System.in);
		int K = sc.nextInt();
		String S = sc.next();

		if(S.length()<K) {
			System.out.println(S);
		}else {
			System.out.println(S.substring(0,K)+"...");
		}

	}

	//	//二分探索
	//k <= num となる最小の配列要素kのインデックスを返す
	static private int binarySearch(long num, long[] orderedArray){
		int lowerBorder = -1;
		int upperBorder = orderedArray.length;
		int mid;

		while(upperBorder - lowerBorder >1) {
			mid = (upperBorder + lowerBorder)/2;
			if(orderedArray[mid]<=num) {
				lowerBorder = mid;
			}else {
				upperBorder = mid;
			}
		}
		return lowerBorder;
	}

	//二分探索
	//k <= num となる最小のList要素kのインデックスを返す
	static private int binarySearch(long num, ArrayList<Long> orderedList){
		int lowerBorder = -1;
		int upperBorder = orderedList.size();
		int mid;

		while(upperBorder - lowerBorder >1) {
			mid = (upperBorder + lowerBorder)/2;
			if(orderedList.get(mid)<=num) {
				lowerBorder = mid;
			}else {
				upperBorder = mid;
			}
		}
		return lowerBorder;
	}

	//aとbの最小公倍数を求める
	public static int gcd(int a, int b) {
        return b == 0 ? a: gcd(b, a % b);
	}
	public static long gcd(long a, long b) {
        return b == 0 ? a: gcd(b, a % b);
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int k = sc.nextInt();
		String s = sc.next();
		sc.close();
		if(k >= s.length()) {
			System.out.println(s);
		} else {
			System.out.println(s.substring(0,k)+"...");
		}

	}

}


import java.util.*;

public class Main {
    static Scanner scanner;

    public static void main(String[] args) {
        scanner = new Scanner(System.in);
        int k = nextInt();
        String s = scanner.next();
        if (s.length() > k) {
            System.out.println(s.substring(0,k) + "...");
        } else {
            System.out.println(s);
        }
    }

    public static boolean rikai(List<Integer> rikaido,int x) {

        System.out.println("c" + rikaido);

        boolean ret = true;
        for (Integer r :rikaido){
            if (r < x) {
                ret = false;
                break;
            }
        }
        return ret;
    }

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

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

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

    public static short nextShort() {
        return Short.parseShort(scanner.next());
    }

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

    public static void printYes() {
        System.out.println("Yes");
    }

    public static void printYES() {
        System.out.println("YES");
    }

    public static void printNo() {
        System.out.println("No");
    }

    public static void printNO() {
        System.out.println("NO");
    }

    public static void nextLine() {
        scanner.nextLine();
    }
}


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();
		int h = sc.nextInt();
		int m = sc.nextInt();
		double Mangle = (m*360)/60;
		double Hangle = (h*60+m)*360/(12*60);
		double MHangle = 0;
		if(Hangle-Mangle>180) {
			MHangle = 360-(Hangle-Mangle);
		}else {
			MHangle = Hangle-Mangle;
		}
		double cosA = Math.cos(MHangle*(Math.PI/180));

		double answer = (a*a)+(b*b)-(2*a*b*cosA);
		double ans = Math.sqrt(answer);

		System.out.println(ans);

	}
}

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


import java.util.Scanner;

public class Main {

	static long bignum = 1000000000+7;

	public static void main(String[] args){

		Scanner sc = new Scanner(System.in);

		double a = sc.nextDouble();
		double b = sc.nextDouble();
		double h = sc.nextDouble();
		double m = sc.nextDouble();

		double degree = ((h+m/60)*30-m*6)/360*2*Math.PI;
		double height = Math.sin(degree)*a;
		double width = b-Math.cos(degree)*a;

		double ans = Math.pow(Math.pow(height, 2)+Math.pow(width, 2),0.5);

		System.out.println(ans);

	}

	static long divn(int target, int times) {//10_9+7のあまり累乗版
		int sqtimes = (int)Math.sqrt(times);
		long ans = 1;
		for(int i =0;i<sqtimes;i++) {
			ans = (ans * target)%(1000000000+7);
		}
		long holder = ans;
		ans = 1;
		for(int i =0;i<sqtimes;i++) {
			ans = (ans*holder)%(1000000000+7);
		}
		for(int i=0;i<times - sqtimes*sqtimes;i++) {
			ans = (ans * target)%(1000000000+7);
		}
		return ans;
	}

	static long div(long a) {//10_9+7のあまり
		if(a<0)a+=1000000000+7;
		return a%(1000000000+7);
	}

}
/*
class City{
	int order;
	int prefecture;
	int year;
	int number;
	City(int order,int prefecture, int year){
		this.order = order;
		this.prefecture = prefecture;
		this.year = year;
	}
}
*/


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.TreeMap;

public class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] sa = br.readLine().split(" ");
		int n = Integer.parseInt(sa[0]);
		int m = Integer.parseInt(sa[1]);
		int[] a = new int[n];
		int[] b = new int[n];
		int[] c = new int[n];
		for (int i = 0; i < n; i++) {
			sa = br.readLine().split(" ");
			a[i] = Integer.parseInt(sa[0]);
			b[i] = Integer.parseInt(sa[1]);
			c[i] = Integer.parseInt(sa[2]);
		}
		int[] d = new int[m];
		int[] e = new int[m];
		int[] f = new int[m];
		for (int i = 0; i < m; i++) {
			sa = br.readLine().split(" ");
			d[i] = Integer.parseInt(sa[0]);
			e[i] = Integer.parseInt(sa[1]);
			f[i] = Integer.parseInt(sa[2]);
		}
		br.close();

		TreeMap<Integer, Integer> mapx = new TreeMap<>();
		mapx.put(0, null);
		for (int i = 0; i < n; i++) {
			mapx.put(a[i], null);
			mapx.put(b[i], null);
		}
		for (int i = 0; i < m; i++) {
			mapx.put(d[i], null);
		}
		Integer[] arr = mapx.keySet().toArray(new Integer[0]);
		int cnt = 0;
		for (Integer i : arr) {
			mapx.put(i, cnt);
			cnt++;
		}
		int[] tox = new int[mapx.size()];
		for (Integer key : mapx.keySet()) {
			tox[mapx.get(key)] = key;
		}

		TreeMap<Integer, Integer> mapy = new TreeMap<>();
		mapy.put(0, null);
		for (int i = 0; i < n; i++) {
			mapy.put(c[i], null);
		}
		for (int i = 0; i < m; i++) {
			mapy.put(e[i], null);
			mapy.put(f[i], null);
		}
		arr = mapy.keySet().toArray(new Integer[0]);
		cnt = 0;
		for (Integer i : arr) {
			mapy.put(i, cnt);
			cnt++;
		}
		int[] toy = new int[mapy.size()];
		for (Integer key : mapy.keySet()) {
			toy[mapy.get(key)] = key;
		}

		boolean[][] ngy = new boolean[tox.length + 1][toy.length + 1];
		for (int i = 0; i < n; i++) {
			int x1 = mapx.get(a[i]);
			int x2 = mapx.get(b[i]);
			int y = mapy.get(c[i]);
			for (int j = x1 + 1; j <= x2; j++) {
				ngy[j][y] = true;
			}
		}

		boolean[][] ngx = new boolean[tox.length + 1][toy.length + 1];
		for (int i = 0; i < m; i++) {
			int x = mapx.get(d[i]);
			int y1 = mapy.get(e[i]);
			int y2 = mapy.get(f[i]);
			for (int j = y1 + 1; j <= y2; j++) {
				ngx[x][j] = true;
			}
		}

		boolean[][] visit = new boolean[tox.length + 1][toy.length + 1];
		int fx = mapx.get(0);
		int fy = mapy.get(0);
		if (fx == 0 || fx == tox.length - 1 || fy == 0 || fy == toy.length - 1) {
			System.out.println("INF");
			return;
		}

		Queue<Integer> que = new ArrayDeque<>();
		que.add(fx * 10000 + fy);
		visit[fx][fy] = true;
		while (!que.isEmpty()) {
			int cur = que.poll();
			int cx = cur / 10000;
			int cy = cur % 10000;
			// 上
			int nx = cx - 1;
			int ny = cy;
			if (!ngx[nx][ny] && !visit[nx][ny]) {
				if (nx == 0) {
					System.out.println("INF");
					return;
				}
				que.add(nx * 10000 + ny);
				visit[nx][ny] = true;
			}
			// 下
			nx = cx + 1;
			ny = cy;
			if (!ngx[cx][ny] && !visit[nx][ny]) {
				if (nx == tox.length) {
					System.out.println("INF");
					return;
				}
				que.add(nx * 10000 + ny);
				visit[nx][ny] = true;
			}
			// 左
			nx = cx;
			ny = cy - 1;
			if (!ngy[nx][ny] && !visit[nx][ny]) {
				if (ny == 0) {
					System.out.println("INF");
					return;
				}
				que.add(nx * 10000 + ny);
				visit[nx][ny] = true;
			}
			// 右
			nx = cx;
			ny = cy + 1;
			if (!ngy[nx][cy] && !visit[nx][ny]) {
				if (ny == toy.length) {
					System.out.println("INF");
					return;
				}
				que.add(nx * 10000 + ny);
				visit[nx][ny] = true;
			}
		}

		long ans = 0;
		for (int i = 1; i < tox.length; i++) {
			for (int j = 1; j < toy.length; j++) {
				if (visit[i][j]) {
					long dx = tox[i] - tox[i - 1];
					long dy = toy[j] - toy[j - 1];
					ans += dx * dy;
				}
			}
		}
		System.out.println(ans);
	}
}

Score: 600 points

Problem Statement

There is a grass field that stretches infinitely.

In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).

There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).

What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead.

Constraints

All values in input are integers between -10^9 and 10^9 (inclusive).

1 \leq N, M \leq 1000

A_i < B_i\ (1 \leq i \leq N)

E_j < F_j\ (1 \leq j \leq M)

The point (0, 0) does not lie on any of the given segments.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M

Output

If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}.

(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)

Sample Input 1

5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4

Sample Output 1

13

The area of the region the cow can reach is 13\ \mathrm{cm^2}.

Sample Input 2

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

Sample Output 2

INF

The area of the region the cow can reach is infinite.


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

class Solver {
  final int n, m;
  final int[][] abcs, defs;

  Solver(int n, int m, int[][] abcs, int[][] defs) {
    this.n = n;
    this.m = m;
    this.abcs = abcs;
    this.defs = defs;
  }

  private static final int[] DX = new int[]{1, 0, -1, 0};
  private static final int[] DY = new int[]{0, 1, 0, -1};

  public String solve() {
    Set<Integer> xSet = new HashSet<>();
    Set<Integer> ySet = new HashSet<>();
    xSet.add(-2_000_000_000);
    xSet.add(2_000_000_000);
    ySet.add(-2_000_000_000);
    ySet.add(2_000_000_000);
    for (int[] abc : abcs) {
      int a = abc[0];
      int b = abc[1];
      int c = abc[2];
      xSet.add(a);
      xSet.add(b);
      ySet.add(c);
    }
    for (int[] def : defs) {
      int d = def[0];
      int e = def[1];
      int f = def[2];
      xSet.add(d);
      ySet.add(e);
      ySet.add(f);
    }
    int xSize = xSet.size();
    int ySize = ySet.size();
    List<Integer> xList = new ArrayList<>();
    List<Integer> yList = new ArrayList<>();
    xList.addAll(xSet);
    yList.addAll(ySet);
    xSet = null;
    ySet = null;
    Collections.sort(xList);
    Collections.sort(yList);
    Map<Integer, Integer> xMap = new HashMap<>();
    Map<Integer, Integer> yMap = new HashMap<>();
    for (int i = 0; i < xSize; i++) {
      xMap.put(xList.get(i), i);
    }
    for (int i = 0; i < ySize; i++) {
      yMap.put(yList.get(i), i);
    }

    boolean[][] blocker = new boolean[2 * xSize][2 * ySize];
    for (int i = 0; i < xSize; i++) {
      for (int j = 0; j < ySize; j++) {
        blocker[2 * i][2 * j] = true;
      }
    }
    for (int[] def : defs) {
      int d = def[0];
      int e = def[1];
      int f = def[2];
      int xIndex = xMap.get(d);
      int yIndexMin = yMap.get(e);
      int yIndexMax = yMap.get(f);
      for (int y = yIndexMin; y < yIndexMax; y++) {
        blocker[2 * xIndex][2 * y + 1] = true;
      }
    }
    for (int[] abc : abcs) {
      int a = abc[0];
      int b = abc[1];
      int c = abc[2];
      int yIndex = yMap.get(c);
      int xIndexMin = xMap.get(a);
      int xIndexMax = xMap.get(b);
      for (int x = xIndexMin; x < xIndexMax; x++) {
        blocker[2 * x + 1][2 * yIndex] = true;
      }
    }
    xMap = null;
    yMap = null;

    int startXIndex = -1;
    for (int i = 1; i < xSize; i++) {
      if (xList.get(i - 1) < 0 && 0 <= xList.get(i)) {
        startXIndex = 2 * (i - 1) + 1;
        break;
      }
    }

    int startYIndex = -1;
    for (int i = 1; i < ySize; i++) {
      if (yList.get(i - 1) < 0 && 0 <= yList.get(i)) {
        startYIndex = 2 * (i - 1) + 1;
        break;
      }
    }

    long answer = 0;
    Deque<Integer> xIndexStack = new ArrayDeque<>();
    Deque<Integer> yIndexStack = new ArrayDeque<>();
    boolean[][] enqueued = new boolean[2 * xSize][2 * ySize];
    enqueued[startXIndex][startYIndex] = true;
    xIndexStack.add(startXIndex);
    yIndexStack.add(startYIndex);
    while (!xIndexStack.isEmpty()) {
      int xIndex = xIndexStack.pollLast();
      int yIndex = yIndexStack.pollLast();
      if (xIndex == 0 || yIndex == 0 || xIndex == 2 * xSize - 1 || yIndex == 2 * ySize - 1) {
        return "INF";
      }
      if (xIndex % 2 == 1 && yIndex % 2 == 1) {
        long xMax = xList.get(xIndex / 2 + 1);
        long xMin = xList.get(xIndex / 2);
        long yMax = yList.get(yIndex / 2 + 1);
        long yMin = yList.get(yIndex / 2);
        answer += (xMax - xMin) * (yMax - yMin);
      }
      for (int k = 0; k < 4; k++) {
        int nextXIndex = xIndex + DX[k];
        int nextYIndex = yIndex + DY[k];
        if (!blocker[nextXIndex][nextYIndex] && !enqueued[nextXIndex][nextYIndex]) {
          enqueued[nextXIndex][nextYIndex] = true;
          xIndexStack.add(nextXIndex);
          yIndexStack.add(nextYIndex);
        }
      }
    }
    return Long.toString(answer);
  }
}

public class Main {
  private static void execute(ContestReader reader, ContestWriter out) {
    int n = reader.nextInt();
    int m = reader.nextInt();
    int[][] abcs = reader.nextInt(n, 3);
    int[][] defs = reader.nextInt(m, 3);
    out.println(new Solver(n, m, abcs, defs).solve());
  }

  public static void main(String[] args) {
    ContestReader reader = new ContestReader(System.in);
    ContestWriter out = new ContestWriter(System.out);
    execute(reader, out);
    out.flush();
  }
}

class ContestWriter extends PrintWriter {
  ContestWriter(PrintStream printeStream) {
    super(printeStream);
  }

  public void printList(List<? extends Object> list) {
    for (Object object : list) {
      println(object);
    }
  }

  public void printListOneLine(List<? extends Object> list) {
    List<String> stringList = new ArrayList<>();
    for (Object object : list) {
      stringList.add(object.toString());
    }
    println(String.join(" ", stringList));
  }
}

class ContestReader {
  private static final int BUFFER_SIZE = 1024;

  private final InputStream stream;
  private final byte[] buffer;
  private int pointer;
  private int bufferLength;

  ContestReader(InputStream stream) {
    this.stream = stream;
    this.buffer = new byte[BUFFER_SIZE];
    this.pointer = 0;
    this.bufferLength = 0;
  }

  private boolean hasNextByte() {
    if (pointer < bufferLength) {
      return true;
    }

    pointer = 0;
    try {
      bufferLength = stream.read(buffer);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return bufferLength > 0;
  }

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

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

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

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

  public String nextLine() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }
    StringBuilder sb = new StringBuilder();
    while(true) {
      int b = readByte();
      if (!isPrintableChar(b) && b != 0x20) {
        break;
      }
      sb.appendCodePoint(b);
    }
    return sb.toString();
  }

  public char nextChar() {
    return next().charAt(0);
  }

  public int nextInt() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }

    int n = 0;
    boolean minus = false;

    {
      int b = readByte();
      if (b == '-') {
        minus = true;
      } else if ('0' <= b && b <= '9') {
        n = b - '0';
      } else {
        throw new NumberFormatException();
      }
    }

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

  public long nextLong() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }

    long n = 0;
    boolean minus = false;

    {
      int b = readByte();
      if (b == '-') {
        minus = true;
      } else if ('0' <= b && b <= '9') {
        n = b - '0';
      } else {
        throw new NumberFormatException();
      }
    }

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

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

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

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

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

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

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

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

  public char[] nextCharArray() {
    return next().toCharArray();
  }

  public String[][] next(int n, int m) {
    String[][] matrix = new String[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = next();
      }
    }
    return matrix;
  }

  public int[][] nextInt(int n, int m) {
    int[][] matrix = new int[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextInt();
      }
    }
    return matrix;
  }

  public char[][] nextChar(int n, int m) {
    char[][] matrix = new char[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextChar();
      }
    }
    return matrix;
  }

  public long[][] nextLong(int n, int m) {
    long[][] matrix = new long[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextLong();
      }
    }
    return matrix;
  }

  public double[][] nextDouble(int n, int m) {
    double[][] matrix = new double[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextDouble();
      }
    }
    return matrix;
  }

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


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        if(b.substring(0, b.length()-1).equals(a)) System.out.println("Yes");
        else System.out.println("No");
    }
}

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


import java.util.*;

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

        Scanner scanner = new Scanner(System.in);
        String S = scanner.next();
        String T = scanner.next();

        if(T.contains(S) && S.charAt(0)==T.charAt(0)){
            System.out.println("Yes");
        }else{
            System.out.println("No");
        }

    }
}


import java.util.*;

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

    String s = sc.next();
    String t = sc.next();
    String ans = "No";

    if(t.substring(0, s.length()).equals(s)){
      ans = "Yes";
    }

    System.out.println(ans);
  }
}


import java.util.Scanner;

public 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();
		int k = sc.nextInt();
		int res = 0;
		if (k - a <= 0) {
			System.out.println(k);
		} else {
			res += a;
			k -= a;
			if (k - b <= 0) {
				System.out.println(res);
			} else {
				k -= b;
				System.out.println(res + -1 * k);
			}
		}
	}
}

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000


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

public class Main {
    void solve(MyScanner in, MyWriter out) {
        long a = in.nextLong();
        long b = in.nextLong();
        long c = in.nextLong();
        long k = in.nextLong();
        long answer = 0;
        answer += 1 * Math.min(a, k);
        k = Math.max(0, k - a);
        k = Math.max(0, k - b);
        answer += -1 * Math.min(c, k);
        out.println(answer);
    }
    public static void main(String[] args) {
        MyWriter w = new MyWriter(System.out);
        new Main().solve(new MyScanner(System.in), w);
        w.flush();
    }
    static final class MyScanner {
        static final int BUFFER_SIZE = 8192;
        private final InputStream in;
        private final byte[] buffer = new byte[BUFFER_SIZE];
        private int point;
        private int readLength;

        MyScanner(InputStream in) {
            this.in = in;
        }
        private int readByte() {
            if (point < readLength) {
                int result = buffer[point];
                point += 1;
                return result;
            }
            try {
                readLength = in.read(buffer);
            } catch (IOException e) {
                throw new AssertionError(null, e);
            }
            if (readLength == -1) {
                return -1;
            }
            point = 1;
            return buffer[0];
        }
        private static boolean isVisibleChar(int c) {
            return 33 <= c && c <= 126;
        }
        char nextChar() {
            int c = readByte();
            while (!(c == -1 || isVisibleChar(c))) {
                c = readByte();
            }
            if (c == -1) {
                throw new NoSuchElementException();
            }
            return (char)c;
        }
        String next() {
            return next(16);
        }
        String next(int n) {
            int c = readByte();
            while (!(c == -1 || isVisibleChar(c))) {
                c = readByte();
            }
            if (c == -1) {
                throw new NoSuchElementException();
            }
            StringBuilder b = new StringBuilder(n);
            do {
                b.append((char)c);
                c = readByte();
            } while (c != -1 && isVisibleChar(c));
            return b.toString();
        }
        long nextLong() {
            int c = readByte();
            while (!(c == -1 || isVisibleChar(c))) {
                c = readByte();
            }
            if (c == -1) {
                throw new NoSuchElementException();
            }
            boolean minus = false;
            long limit = -Long.MAX_VALUE;
            if (c == '-') {
                minus = true;
                limit = Long.MIN_VALUE;
                c = readByte();
            }
            long n = 0L;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                if (n < limit / 10L) {
                    throw new InputMismatchException();
                }
                n *= 10L;
                int digit = c - '0';
                if (n < limit + digit) {
                    throw new InputMismatchException();
                }
                n -= digit;
                c = readByte();
            } while (c != -1 && isVisibleChar(c));
            return minus ? n : -n;
        }
        int nextInt() {
            long n = nextLong();
            if (n < Integer.MIN_VALUE || n > Integer.MAX_VALUE) {
                throw new InputMismatchException();
            }
            return (int)n;
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        int[] nextIntArray(int n) {
            int[] result = new int[n];
            for (int i = 0; i < n; i++) {
                result[i] = nextInt();
            }
            return result;
        }
        long[] nextLongArray(int n) {
            long[] result = new long[n];
            for (int i = 0; i < n; i++) {
                result[i] = nextLong();
            }
            return result;
        }
        char[] nextCharArray(int n) {
            char[] result = new char[n];
            for (int i = 0; i < n; i++) {
                result[i] = nextChar();
            }
            return result;
        }
        char[][] next2dCharArray(int n, int m) {
            char[][] result = new char[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    result[i][j] = nextChar();
                }
            }
            return result;
        }
        int[][] nextVerticalIntArrays(int arrayCount, int arrayLength) {
            int[][] result = new int[arrayCount][arrayLength];
            for (int i = 0; i < arrayLength; i++) {
                for (int j = 0; j < arrayCount; j++) {
                    result[j][i] = nextInt();
                }
            }
            return result;
        }
        long[][] nextVerticalLongArrays(int arrayCount, int arrayLength) {
            long[][] result = new long[arrayCount][arrayLength];
            for (int i = 0; i < arrayLength; i++) {
                for (int j = 0; j < arrayCount; j++) {
                    result[j][i] = nextLong();
                }
            }
            return result;
        }
        char[][] nextVerticalCharArrays(int arrayCount, int arrayLength) {
            char[][] result = new char[arrayCount][arrayLength];
            for (int i = 0; i < arrayLength; i++) {
                for (int j = 0; j < arrayCount; j++) {
                    result[j][i] = nextChar();
                }
            }
            return result;
        }
    }
    static final class MyWriter extends PrintWriter {
        MyWriter(OutputStream out) {
            super(out);
        }
        void println(int[] x) {
            println(x, " ");
        }
        void println(int[] x, String delimiter) {
            if (x.length > 0) {
                print(x[0]);
                for (int i = 1; i < x.length; i++) {
                    print(delimiter);
                    print(x[i]);
                }
            }
            println();
        }
        void println(long[] x) {
            println(x, " ");
        }
        void println(long[] x, String delimiter) {
            if (x.length > 0) {
                print(x[0]);
                for (int i = 1; i < x.length; i++) {
                    print(delimiter);
                    print(x[i]);
                }
            }
            println();
        }
        void println(Iterable<?> iterable) {
            println(iterable, " ");
        }
        void println(Iterable<?> iterable, String delimiter) {
            Iterator<?> i = iterable.iterator();
            if (i.hasNext()) {
                print(i.next());
                while (i.hasNext()) {
                    print(delimiter);
                    print(i.next());
                }
            }
            println();
        }
        void printLines(int[] x) {
            println(x, System.lineSeparator());
        }
        void printLines(long[] x) {
            println(x, System.lineSeparator());
        }
        void printLines(Iterable<?> iterable) {
            println(iterable, System.lineSeparator());
        }
    }
}


import java.util.*;

public class Main {

    static int gcd (int a, int b) {return b>0?gcd(b,a%b):a;}
    static int mod = 1000000007;

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

        if(A >= K){
            System.out.println(K);
        } else if(A + B >= K){
            System.out.println(A);
        } else {
            System.out.println(A - (K - A - B));
        }
    }

}


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();
		int c=sc.nextInt();
		int k=sc.nextInt();

		int ans=0;

		if(k<=a)ans=k;
		else if(k<a+b)ans=a;
		else if(k<a+b+c)ans=a-(k-a-b);

		System.out.println(ans);

	}

}


import java.util.Scanner;
public class Main {
	static int[][] gyo2=new int[100000][12];
	static int count=0;
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int N=sc.nextInt();
		int M=sc.nextInt();
		long X=sc.nextLong();
		int C[]=new int[N];
		int A[][]=new int[N][M];
		for(int i=0;i<N;i++) {
			C[i]=sc.nextInt();
			for(int j=0;j<M;j++) {
				A[i][j]=sc.nextInt();
			}
		}
		int gyo[]=new int[N];
		zenbit(0,N,gyo);
		long ans=1000000000;
		boolean flag=true;
		boolean kuso=false;
		for(int i=0;i<count;i++) {
			int money=0;
			int kari[]=new int[M];
			for(int j=0;j<N;j++) {
			if(gyo2[i][j]==1) {
				for(int z=0;z<M;z++) {
				kari[z]+=A[j][z];
				}
				money+=C[j];
			}
				}
			for(int j=0;j<M;j++) {
				if(X>kari[j]) {
					flag=false;
					//System.out.println(money);
					//System.out.println(kari[j]);
				}
			}
			if(flag) {kuso=true;
			}
			if(flag&&(ans>money)) {
				ans=money;
			}
			flag=true;
		}
		if(kuso) {
			System.out.println(ans);
		}else {
			System.out.println(-1);
		}

}
	public static void zenbit(int kosu,int N,int gyo[]) {
		if(kosu<N) {
			gyo[kosu]=0;
			zenbit(kosu+1,N,gyo);
			gyo[kosu]=1;
			zenbit(kosu+1,N,gyo);
		}else {
			for(int i=0;i<N;i++) {
				gyo2[count][i]=gyo[i];
			}
			count++;
			return;
		}
	}

}

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

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

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067