import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		String A = sc.next();
		String B = sc.next();
		String C = sc.next();
		String[] strArraySubA = A.split("");
		String[] strArrayA = new String[A.length()];
		int count = 0;
		for (int i = 0; i < strArraySubA.length; i++) {
		    strArrayA[i] = strArraySubA[i];
		}
		String[] strArraySubB = B.split("");
		String[] strArrayB = new String[B.length()];
		for (int i = 0; i < strArraySubB.length; i++) {
		    strArrayB[i] = strArraySubB[i];
		}
		String[] strArraySubC = A.split("");
		String[] strArrayC = new String[A.length()];

		for (int i = 0; i < strArrayA.length; i++) {
		    // "strArray"を1文字ずつ表示
		    System.out.println("strArrayの要素番号" + i + "の時：" + strArrayA[i]);
		}
		for (int i = 0; i < strArrayB.length; i++) {
		    // "strArray"を1文字ずつ表示
		    System.out.println("strArrayの要素番号" + i + "の時：" + strArrayB[i]);
		}
		for (int i = 0; i < strArraySubC.length; i++) {
		    strArrayC[i] = strArraySubC[i];
		}
		for(int i = 0; i<N;i++) {
			if(strArrayA[i].equals(strArrayB[i])) {

			}else {
				strArrayB[i]=strArrayA[i];
				count ++;
			}
		}
		for(int i = 0; i<N;i++) {
			if(strArrayA[i].equals(strArrayC[i])) {

			}else {
				strArrayC[i]=strArrayA[i];
				count ++;
			}
		}
		System.out.println(count);

//		for (int i = 0; i < strArrayA.length; i++) {
//		    // "strArray"を1文字ずつ表示
//		    System.out.println("strArrayの要素番号" + i + "の時：" + strArrayA[i]);
//		}
//		for (int i = 0; i < strArrayB.length; i++) {
//		    // "strArray"を1文字ずつ表示
//	    System.out.println("strArrayの要素番号" + i + "の時：" + strArrayB[i]);
//		}
//		for (int i = 0; i < strArrayC.length; i++) {
//		    // "strArray"を1文字ずつ表示
//	    System.out.println("strArrayの要素番号" + i + "の時：" + strArrayC[i]);
//		}

//		int N = sc.nextInt();
//		int A = sc.nextInt();
//		int B = sc.nextInt();
//		int max=0;
//		int min=0;
//		if(N >= 1 && N<=100) {
////		nがa+b以下
//			if(A+B<=N) {
//				if(A>B) {
//					max = B;
//					min = 0;
//				}else if (A<=B) {
//					max = A;
//					min = 0;
//				}
//			}
////
//			if(A+B>N) {
//				if(A>=B) {
//					max = B;
//					min = (A+B)-N;
//				}else if(A<B) {
//					max = A;
//					min = (A+B)-N;
//				}
//			}
//			if(A==B && A==N) {
//				max = N;
//				min = N;
//			}
//		}
//		System.out.println(max +" "+ min);

	}
}

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


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

class Main {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    long[] a = new long[n];
    long[] b = new long[n];
    for (int i = 0; i < n; i++) {
      a[i] = scanner.nextLong();
      b[i] = scanner.nextLong();
    }
    scanner.close();
    long allB = 0;
    for (long l : b) {
      allB += l;
    }
    long[] ab = new long[n];
    for (int i = 0; i < n; i++) {
      ab[i] = a[i] + b[i];
    }
    Arrays.sort(ab);
    long p = 0;
    for (int i = 0; i < n; i += 2) {
      p += ab[ab.length - i - 1];
    }
    System.out.println(-allB + p);
  }

}

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

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.

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.


//package AtCoder.Nekkei;

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

class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int m = s.nextInt();
        boolean[] visited = new boolean[n + 1];
        int[] parent = new int[n + 1];
        Arrays.fill(parent, -1);
        pair[] arr = new pair[n + m - 1];
        HashSet<Integer> set = new HashSet<>();
        for (int i = 1; i <= n; i++) {
//            H
            set.add(i);
        }
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();

        for (int i = 0; i < n + m - 1; i++) {
            int first = s.nextInt() ;
            int secon = s.nextInt() ;
            arr[i] = new pair(first, secon);
            if(set.contains(secon)) {
                set.remove(secon);
            }
            ArrayList<Integer> list = map.getOrDefault(first, new ArrayList<>());
            list.add(secon);
            map.put(first, list);
        }
        int[] val = new int[n + 1];
        Arrays.fill(val, -1);
        Iterator<Integer> iter = set.iterator();
        int num = -1;
//        iter.forEachRemaining(integer -> val[integer] = 0);
        while(iter.hasNext()) {
            int nu = iter.next();
            if(nu != 0) {
                val[nu] = 0;
            }
        }
        for (int i = 1; i < val.length; i++) {
            if(val[i] == 0){

                num = i;
                break;
            }
        }
        parent[num] = 0;
//        System.out.println(num);
        dfs(num, visited, parent, map);
//        System.out.println(Arrays.toString(parent));
        StringBuilder ans = new StringBuilder();
        for (int i = 1; i < parent.length; i++) {
            ans.append(parent[i] + "\n");
        }
        System.out.println(ans.toString());
    }

    private static void dfs(int num, boolean[] visited, int[] parent, HashMap<Integer, ArrayList<Integer>> map) {
        if(visited[num]){
            return;
        }
        visited[num] = true;
        ArrayList<Integer> list = map.getOrDefault(num, new ArrayList<>());
        for (int i = 0; i < list.size(); i++) {
            int curr = list.get(i);
            if(!visited[curr]){
//                visited[curr] = true;
                parent[curr] = num;
                dfs(curr, visited, parent, map);
            }
        }
    }

    private static class pair {
        int src;
        int dest;

        public pair(int src, int dest) {
            this.src = src;
            this.dest = dest;
        }

        @Override
        public boolean equals(Object obj) {
            pair p = (pair) obj;
            return this.dest == p.dest && this.src == p.src;
        }

    }
}

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


// package other2019.nikkei2019.qual;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class Main {
    static long __startTime = System.currentTimeMillis();

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

        int n = in.nextInt();
        int m = in.nextInt();
        long[] x = new long[n];
        for (int i = 0; i < n ; i++) {
            x[i] = in.nextLong();
        }
        int[][] edges = new int[m][3];
        for (int i = 0; i < m ; i++) {
            for (int j = 0; j < 2 ; j++) {
                edges[i][j] = in.nextInt()-1;
            }
            edges[i][2] = in.nextInt();
        }
        Arrays.sort(edges, Comparator.comparingInt(u -> u[2]));

        UnionFind uf = new UnionFind(n, x);

        int[] canUse = new int[m];
        for (int i = 0; i < m; i++) {
            int u = edges[i][0];
            int v = edges[i][1];
            uf.unite(u, v);
            int nid = uf.find(u);
            if (uf.groupCount(nid) >= edges[i][2]) {
                canUse[i] = 2;
            }
        }

        List<Integer>[] graph = new List[n];
        for (int i = 0; i < n ; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int i = 0; i < m ; i++) {
            graph[edges[i][0]].add(i);
            graph[edges[i][1]].add(i);
        }

        Queue<Integer> q = new ArrayBlockingQueue<>(n + m + 10);
        boolean[] visited = new boolean[n];
        for (int i = m-1 ; i >= 0 ; i--) {
            if (canUse[i] == 2) {
                q.add(edges[i][0]);
                q.add(edges[i][1]);
                while (q.size() >= 1) {
                    int now = q.poll();
                    for (int eid : graph[now]) {
                        int to = edges[eid][0] + edges[eid][1] - now;
                        if (edges[eid][2] > edges[i][2]) {
                            continue;
                        }
                        canUse[eid] = Math.max(canUse[eid], 1);
                        if (!visited[to]) {
                            visited[to] = true;
                            q.add(to);
                        }
                    }
                }
            }
        }

        int ecount = 0;
        for (int i = 0; i < m ; i++) {
            ecount += canUse[i] >= 1 ? 1 : 0;
        }
        out.println(m-ecount);
        out.flush();
    }

    static class UnionFind {
        int[] rank;
        int[] parent;
        long[] cnt;

        public UnionFind(int n, long[] x) {
            rank = new int[n];
            parent = new int[n];
            cnt = new long[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                cnt[i] = x[i];
            }
        }

        public int find(int a) {
            if (parent[a] == a) {
                return a;
            }
            parent[a] = find(parent[a]);
            cnt[a] = cnt[parent[a]];
            return parent[a];
        }

        public void unite(int a, int b) {
            a = find(a);
            b = find(b);
            if (a == b) {
                return;
            }
            if (rank[a] < rank[b]) {
                parent[a] = b;
                cnt[b] += cnt[a];
            } else {
                parent[b] = a;
                cnt[a] += cnt[b];
                if (rank[a] == rank[b]) {
                    rank[a]++;
                }
            }
        }

        public long groupCount(int a) {
            return cnt[find(a)];
        }

        private boolean issame(int a, int b) {
            return find(a) == find(b);
        }
    }

    private static void printTime(String label) {
        debug(label, System.currentTimeMillis() - __startTime);
    }

    private static void debug(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }

    public static class InputReader {
        private static final int BUFFER_LENGTH = 1 << 12;
        private InputStream stream;
        private byte[] buf = new byte[BUFFER_LENGTH];
        private int curChar;
        private int numChars;

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

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

        public char nextChar() {
            return (char) skipWhileSpace();
        }

        public String nextToken() {
            int c = skipWhileSpace();
            StringBuilder res = new StringBuilder();
            do {
                res.append((char) c);
                c = next();
            } while (!isSpaceChar(c));
            return res.toString();
        }

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

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

        public double nextDouble() {
            return Double.valueOf(nextToken());
        }

        int skipWhileSpace() {
            int c = next();
            while (isSpaceChar(c)) {
                c = next();
            }
            return c;
        }

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

Score : 800 points

Problem Statement

There is a connected undirected graph with N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Also, each of these vertices and edges has a specified weight.
Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i.

We would like to remove zero or more edges so that the following condition is satisfied:

For each edge that is not removed, the sum of the weights of the vertices in the connected component containing that edge, is greater than or equal to the weight of that edge.

Find the minimum number of edges that need to be removed.

Constraints

1 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq X_i \leq 10^9

1 \leq A_i < B_i \leq N

1 \leq Y_i \leq 10^9

(A_i,B_i) \neq (A_j,B_j) (i \neq j)

The given graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_N
A_1 B_1 Y_1
A_2 B_2 Y_2
:
A_M B_M Y_M

Output

Find the minimum number of edges that need to be removed.

Sample Input 1

4 4
2 3 5 7
1 2 7
1 3 9
2 3 12
3 4 18

Sample Output 1

2

Assume that we removed Edge 3 and 4.
In this case, the connected component containing Edge 1 contains Vertex 1, 2 and 3, and the sum of the weights of these vertices is 2+3+5=10.
The weight of Edge 1 is 7, so the condition is satisfied for Edge 1.
Similarly, it can be seen that the condition is also satisfied for Edge 2.
Thus, a graph satisfying the condition can be obtained by removing two edges.

The condition cannot be satisfied by removing one or less edges, so the answer is 2.

Sample Input 2

6 10
4 4 1 1 1 7
3 5 19
2 5 20
4 5 8
1 6 16
2 3 9
3 6 16
3 4 1
2 6 20
2 4 19
1 2 9

Sample Output 2

4

Sample Input 3

10 9
81 16 73 7 2 61 86 38 90 28
6 8 725
3 10 12
1 4 558
4 9 615
5 6 942
8 9 918
2 7 720
4 7 292
7 10 414

Sample Output 3

8


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int s = sc.nextInt();
		if (s == 2 || s == 1) {
			System.out.println(4);
			return;
		}
		for (int i = 1;;i++) {
			if (s == 4) {
				System.out.println(i+3);
				return;
			} else if (s % 2 == 0) {
				s /= 2;
			} else {
				s = s * 3 + 1;
			}
		}
	}
}

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

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


import java.util.*;
public class Main {
	public static void main(String[]args) {
		Scanner sc=new Scanner(System.in);
      int n=sc.nextInt();
      int count=1;
      while(true){
        count++;
      	if(n%2==0){
          n/=2;
        }
        else{
          n=3*n+1;
        }
        if(n==4||n==1||n==2)break;
      }
      System.out.println(count+3);
	}
}


import java.util.*;

class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String inputString = sc.nextLine();
        int s = Integer.valueOf(inputString);
        if(s==4 || s==2 || s==1 ) {
            System.out.println("4");
            return;
        }
        int lastNumber = s;
        int i = 2;
        while(true) {
            int thisNumber = function(lastNumber);
            if(thisNumber==4) {
                System.out.println(i+3);
                break;
            }
            lastNumber = thisNumber;
            i++;
        }
    }

    private static int function(int n) {
        if(n%2==0){
            return n/2;
        }else{
            return 3*n+1;
        }

    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
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;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        CGrandGarden solver = new CGrandGarden();
        solver.solve(1, in, out);
        out.close();
    }

    static class CGrandGarden {
        int ans = 0;

        public void solve(int testNumber, InputReader in, OutputWriter out) {

            int n = in.nextInt();

            int[] h = new int[n + 1];

            for (int i = 1; i <= n; i++) h[i] = in.nextInt();

            int[] a = new int[n + 1];

            Arrays.fill(a, 0);

            recurse(a, h, 1, n);

            out.println(ans);
        }

        private void recurse(int[] a, int[] h, int start, int n) {
            int s = start;

            // System.out.println(ans);
            if (start > n) {
                return;
            }

            boolean flag = false;
            for (int i = start; i <= n; i++) {
                if (h[i] == 0) {
                    flag = true;
                    recurse(a, h, s, i - 1);
                    s = i + 1;
                }
            }

            if (flag == true) {
                recurse(a, h, s, n);
                return;
            }
            for (int i = start; i <= n; i++) {
                a[i]++;
            }

            ans++;

            for (int i = start; i <= n; i++) {
                if (a[i] == h[i]) {
                    recurse(a, h, s, i - 1);
                    s = i + 1;
                    //   continue;
                }
            }

            recurse(a, h, s, n);
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.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 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 boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

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

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

        }

    }
}

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


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

		for(int i = 0; i < n ; i++) {
			h[i] = sc.nextInt();
		}
		int r , l;
		int count = 0;
		do {
			r = 0; l = 0;
			int flag = 0;
			for(int i = 0; i <= n ; i++) {
				if(h[i] > 0 && flag == 0) {
					flag = 1;
					count++;
					r = i;
				}
				if(h[i] == 0 && flag == 1) {
					flag = 0;
					l = i;
					break;
				}
			}

			for(int i = r; i < l ; i++) {
				h[i] = h[i] - 1;
			}

		}while(r != 0 || l != 0);

		System.out.println(count);
	}
}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int len = sc.nextInt();
		int[] Garden = new int[len];

		for(int i = 0;i < len;i++) {
			Garden[i] = sc.nextInt();
		}

		WaterCount(Garden);
		sc.close();
	}
	public static void WaterCount(int[] Garden){
		int water = 0;
		int cnt = 0;
		int tmp = 0;
		int min;

		while(cnt != Garden.length) {
			for(int i = cnt;i < Garden.length-1;i++) {
				//途中に０がないか探す
				if(Garden[i+1] == 0) {
					tmp =i+1;
					break;
				}
			}
				min = Garden[cnt];
				//0が途中にあったら
				if(tmp != 0) {
					for(int j = cnt + 1;j < tmp;j++) {
						if(Garden[j] < min) {
							min = Garden[j];
						}
					}
					for(int w = 1;w <= min;w++) {
						for(int j = cnt;j < tmp;j++) {
							Garden[j]--;
						}
						water++;
					}
					tmp = 0;
				}else {
					for(int j = cnt + 1;j < tmp;j++) {
						if(Garden[j] < min) {
							min = Garden[j];
						}
					}
					for(int w = 1;w <= min;w++) {
						for(int j = cnt;j < Garden.length;j++) {
							Garden[j]--;
						}
						water++;
					}
				}
				while(Garden[cnt] == 0) {
					cnt++;

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


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;

public class Main {
    public static void main(final String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int counter = scanner.nextInt();
        final int k = scanner.nextInt();
        final Sushi[] sushiArray = new Sushi[counter];

        for (int i = 0; i < counter; i++) {
            final Sushi sushi = new Sushi(scanner.nextInt(), scanner.nextLong());
            sushiArray[i] = sushi;
        }

        Arrays.sort(sushiArray, (o1, o2) -> (int) o2.getDeliciousness() - (int) o1.getDeliciousness());
        final Map<Integer, List<Long>> sushiMap = new HashMap<>();
        final Set<Integer> alreadyIncludedTopping = new HashSet<>();
        long partialAnswer = 0;
        final PriorityQueue<Sushi> allSushi = new PriorityQueue<>(Comparator.comparingInt(a -> (int) a.getDeliciousness()));
        for (int i = 0; i < k; i++) {
            final Sushi sushi = sushiArray[i];
            allSushi.add(sushi);
            partialAnswer += sushi.getDeliciousness();
            alreadyIncludedTopping.add(sushi.getTopping());
            sushiMap.computeIfAbsent(sushi.getTopping(), e -> new ArrayList<>())
                    .add(sushi.getDeliciousness());
        }

        long answer = partialAnswer + sushiMap.size() * sushiMap.size();

        for (int i = k; i < counter; i++) {
            final Sushi sushi = sushiArray[i];
            if (alreadyIncludedTopping.contains(sushi.getTopping())) {
                continue;
            }

            boolean endFlag = false;
            while (true) {
                if (allSushi.isEmpty()) {
                    endFlag = true;
                    break;
                }

                final Sushi poll = allSushi.poll();
                if (sushiMap.get(poll.getTopping()).size() > 1) {
                    alreadyIncludedTopping.add(sushi.getTopping());
                    final long deliciousness = poll.getDeliciousness();
                    final List<Long> list = sushiMap.get(poll.getTopping());
                    list.remove(list.size() - 1);
                    partialAnswer -= deliciousness;
                    partialAnswer += sushi.getDeliciousness();
                    if (partialAnswer + alreadyIncludedTopping.size() * alreadyIncludedTopping.size() > answer) {
                        answer = partialAnswer + alreadyIncludedTopping.size() * alreadyIncludedTopping.size();
                    }
                    break;
                }
            }

            if (endFlag) {
                break;
            }
        }

        System.out.println(answer);
    }

    private static class Sushi {
        private final int topping;
        private final long deliciousness;

        Sushi(final int topping, final long deliciousness) {
            this.topping = topping;
            this.deliciousness = deliciousness;
        }

        int getTopping() {
            return topping;
        }

        long getDeliciousness() {
            return deliciousness;
        }
    }
}

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

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

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

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


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

public class Main {

	static long[] sumLengthOfDigitNumber = new long[19];
	static long[] digit10 = new long[19];

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

		int N = sc.nextInt();
		int K = sc.nextInt();
		Pair[] list = new Pair[N];
		for(int i = 0; i < N; i++){
			list[i] = new Pair(sc.nextInt(), sc.nextInt());
		}

		Arrays.sort(list, (p1, p2)->p2.d-p1.d);

		for(Pair p : list) System.out.println(p.t + " " + p.d);

		long ansSum = 0;
		int ansType = 0;
		HashMap<Integer, Long> map = new HashMap<Integer, Long>();
		for(int i = 0; i < K; i++){
			ansSum += list[i].d;
			Long count = map.get(list[i].t);
			if(count == null) map.put(list[i].t, 1L);
			else map.put(list[i].t, count+1);
		}
		ansType = map.size();
		int index = K-1;

		long ans = (ansType*ansType + ansSum);

		if(K == N){
			System.out.println(ans);
			return;
		}

		//System.out.println("\n" + ansSum + " " + ansType + " " + (ansType*ansType + ansSum));

		Pair[] nokori = new Pair[N-K];
		for(int i = K; i < N; i++) nokori[i-K] = list[i];
		Arrays.sort(nokori, (p1, p2)->p1.compTD(p2));
		//for(Pair p : nokori) System.out.println(p.t + " " + p.d);
		for(Pair p : nokori){

			Long count = map.get(p.t);
			if(count != null) continue;
			//System.out.println("type" + " " + p.t);
			while(index >= 0){
				if(list[index].t != p.t){
					long sum = ansSum - list[index].d + p.d;
					int type = ansType + 1;
					long res = (type*type + sum);
					//System.out.println(sum + " " + type + " " + res);
					ansSum = sum;
					ansType = type;
					ans = Math.max(ans, res);
					index--;

					map.put(p.t, 1L);
					break;
				}else{

				}
			}
			if(map.size() == K) break;
		}

		System.out.println(ans);

	}//end main

}//end Main

class Pair{
	int t, d;
	public Pair(int t, int d){
		this.t = t; this.d = d;
	}

	public int compTD(Pair p){
		if(this.d != p.d){
			return p.d - this.d;
		}else{
			return p.t - this.t;
		}
	}
}

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 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.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

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

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

        out.flush();
    }

}

class AtCoder {

    int a, b, c, d;

    AtCoder(FastScanner sc) {
        a = sc.nextInt();
        b = sc.nextInt();
        c = sc.nextInt();
        d = sc.nextInt();
    }

    void solve(PrintWriter out) {
        Set<Integer> set = new HashSet<>();
        set.add(a);
        set.add(b);
        set.add(c);
        set.add(d);
        if (set.contains(1) && set.contains(9) && set.contains(7) && set.contains(4))
            out.println("YES");
        else out.println("NO");
    }

}

class FastScanner {

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

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

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

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

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

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

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

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

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

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

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

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

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

class My {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static Map<Integer, Integer> tally(int[] array) {
        Map<Integer, Integer> map = new TreeMap<>();
        for (int k : array) {
            int v = map.getOrDefault(k, 0);
            map.put(k, ++v);
        }
        return map;
    }

    static Map<Long, Integer> tally(long[] array) {
        Map<Long, Integer> map = new TreeMap<>();
        for (long k : array) {
            int v = map.getOrDefault(k, 0);
            map.put(k, ++v);
        }
        return map;
    }

    static Map<Double, Integer> tally(double[] array) {
        Map<Double, Integer> map = new TreeMap<>();
        for (double k : array) {
            int v = map.getOrDefault(k, 0);
            map.put(k, ++v);
        }
        return map;
    }

    static Map<String, Integer> tally(String[] array) {
        Map<String, Integer> map = new TreeMap<>();
        for (String k : array) {
            int v = map.getOrDefault(k, 0);
            map.put(k, ++v);
        }
        return map;
    }

    static Map<Character, Integer> tally(char[] array) {
        Map<Character, Integer> map = new TreeMap<>();
        for (char k : array) {
            int v = map.getOrDefault(k, 0);
            map.put(k, ++v);
        }
        return map;
    }

}

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


import java.util.*;

public class Main {
	public static void main(String[] args){
    	Scanner sc = new Scanner(System.in);
		String K = "keyence";
		String S = sc.next();
        boolean fl = false;
        int l = S.length();

      	for(int i=6;0<=i;i--){
        	if(S.substring(0,i)== K.substring(0,i)){
        		if(S.substring(l-(6-i))==K.substring(i)){
                	System.out.println("YES");
                    fl = true;
                  	break;
                }
            }

        }
      	if(!fl){
          System.out.println("NO");
        }
     }
}


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

public class Main {
	public int findWay(int[][] mat,int N,int C,int R,int count,int rI,int cI) {
  		if(rI > N-R ) {
			if(cI < N-C) {
				cI++;
				return findWay(mat, N, C, R, count,0, cI);
			}
			else {
				return count;
			}
		}
		if(rI <= N-C) {
			rI++;
		}else {
			rI = 0;
		}
		count++;
		return findWay(mat, N, C, R, count, rI, cI);
	}
	public static void main(String[] args) throws NumberFormatException, IOException {
		Main ac = new Main();
		int count = 0;
		int N,R=4,C;
		int cI,rI;
		cI = 0;
		rI = 0;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		R = Integer.parseInt(br.readLine());
      	C = Integer.parseInt(br.readLine());
		int mat[][] = new int[N][N];
		System.out.println(ac.findWay(mat, N, C, R, count, rI, cI));
	}
}

Score : 100 points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.

How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?

Constraints

1 \leq H, W \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

### ...
### ###
... ###

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


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

static class Node{
  String s;
  boolean access = false;
  int count = 0;
  Node(String s){
    this.s = s;
  }
}

static class Group{
  int white = 0;
  int black = 1;
  Group(){}
}

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

static void bfs(int y, int x){
  int[] dy = {-1,0,1,0};
  int[] dx = {0,-1,0,1};
  ArrayDeque<QueueObject> queue = new ArrayDeque<QueueObject>();
  queue.add(new QueueObject(y, x));
  list[y][x].access = true;
  list[y][x].count = 0;
  while(queue.size() > 0){
    QueueObject now = queue.pollFirst();
    int nowY = now.y;
    int nowX = now.x;
    for(int i = 0; i < 4; i++){
      int nextY = nowY + dy[i];
      int nextX = nowX + dx[i];
      try{
        if(!list[nextY][nextX].access){
          if(list[nowY][nowX].count % 2 == 0 && list[nextY][nextX].s.equals(".")){
            list[nextY][nextX].count = list[nowY][nowX].count + 1;
            list[nextY][nextX].access = true;
            queue.add(new QueueObject(nextY, nextX));
            Group g = group.get(group.size() - 1);
            g.white++;
            group.set(group.size() - 1, g);
          }else if(list[nowY][nowX].count % 2 == 1 && list[nextY][nextX].s.equals("#")){
            list[nextY][nextX].count = list[nowY][nowX].count + 1;
            list[nextY][nextX].access = true;
            queue.add(new QueueObject(nextY, nextX));
            Group g = group.get(group.size() - 1);
            g.black++;
            group.set(group.size() - 1, g);
          }
        }
      }catch(Exception e){}
    }
  }
}

	//Method addition frame end
}

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


import java.util.*;

class UnionFind {
    static class RootInfo {
        int i;
        int j;
        int depth;

        public RootInfo(int i, int j, int depth) {
            this.i = i;
            this.j = j;
            this.depth = depth;
        }
    }

    int[] body; // This keeps parent number. If it has the index itself, it's a root.
    int h;
    int w;

    public UnionFind(int h, int w) {
        this.body = new int[h * w];
        this.h = h;
        this.w = w;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                this.body[indexOf(i, j)] = indexOf(i, j);
            }
        }
    }

    public void union(int i1, int j1, int i2, int j2) {
        RootInfo root1 = findRoot(i1, j1);
        RootInfo root2 = findRoot(i2, j2);
        if (root1.depth >= root2.depth) { // optimize
            this.body[indexOf(root2.i, root2.j)] = indexOf(root1.i, root1.j);
        } else {
            this.body[indexOf(root1.i, root1.j)] = indexOf(root2.i, root2.j);
        }
    }

    public int findGroup(int i, int j) {
        RootInfo info = findRoot(i, j);
        return indexOf(info.i, info.j);
    }

    private RootInfo findRoot(int i, int j) {
        RootInfo info = findRootInternal(i, j);
        if (info.depth >= 2) { // optimize
            this.body[indexOf(i, j)] = indexOf(info.i, info.j);
        }
        return info;
    }

    private RootInfo findRootInternal(int i, int j) {
        int index = this.body[indexOf(i, j)];
        int nextI = index % h;
        int nextJ = index / h;
        if (i == nextI && j == nextJ) {
            return new RootInfo(i, j, 0);
        } else {
            RootInfo info = findRootInternal(nextI, nextJ);
            info.depth += 1;
            return info;
        }
    }

    private int indexOf(int i, int j) {
        return i + h * j;
    }
}

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] hw = scanner.nextLine().split(" ", 2);
        int h = Integer.parseInt(hw[0]);
        int w = Integer.parseInt(hw[1]);

        boolean[][] black = new boolean[h][w];
        for (int i = 0; i < h; i++) {
            String line = scanner.nextLine();
            for (int j = 0; j < w; j++) {
                black[i][j] = (line.charAt(j) == '#');
            }
        }

        UnionFind groups = new UnionFind(h, w);
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                // left
                if (i - 1 >= 0 && black[i][j] != black[i-1][j]) {
                    groups.union(i, j, i-1, j);
                }

                // right
                if (i + 1 < h && black[i][j] != black[i+1][j]) {
                    groups.union(i, j, i+1, j);
                }

                // up
                if (j - 1 >= 0 && black[i][j] != black[i][j-1]) {
                    groups.union(i, j, i, j-1);
                }

                // down
                if (j + 1 < w && black[i][j] != black[i][j+1]) {
                    groups.union(i, j, i, j+1);
                }
            }
        }

        Map<Integer, Integer> groupBlacks = new HashMap<>();
        Map<Integer, Integer> groupWhites = new HashMap<>();
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                int group = groups.findGroup(i, j);
                if (black[i][j]) {
                    int count = groupBlacks.getOrDefault(group, 0);
                    groupBlacks.put(group, count + 1);
                } else {
                    int count = groupWhites.getOrDefault(group, 0);
                    groupWhites.put(group, count + 1);
                }
            }
        }

        int answer = 0;
        for (Integer group : groupBlacks.keySet()) {
            int blacks = groupBlacks.get(group);
            int whites = groupWhites.getOrDefault(group, 0);
            answer += blacks * whites;
        }
        System.out.println(answer);
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int input[][] = new int[n][3];

		for(int i = 0; i < n; i++){
			for(int j = 0; j < 3; j++){
				input[i][j] = sc.nextInt();
			}
		}

		int dp[][] = new int[n][3];

		for(int i = 0; i < 3; i++){
			dp[0][i] = input[0][i];
		}

		for(int i = 1; i < n; i++){
			for(int j = 0; j < 3; j++){
				dp[i][j] = Math.max(dp[i - 1][(j + 1)%3], dp[i - 1][(j + 2)%3]) + input[i][j];
			}
		}

		System.out.println(Math.max(dp[n - 1][0], Math.max(dp[n - 1][1], dp[n - 1][2])));
	}
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


import java.util.*;
import java.io.*;
public class Main {
//
// public static int frog(int arr[], int i, int prev){
//     if(i >= arr.length)
//           return 0;
//     if(i == arr.length-1)
//         return Math.abs(arr[prev]- arr[i]);
//     int a = 0; int b = 0;
//     if(prev == -1){
//        return Math.min(0+frog(arr,i+1,0),0+frog(arr,i+2,0));
//     }
//
//     else{
//            // System.out.println(arr[prev]+ " - " + arr[i] );
//             a =   Math.abs(arr[prev] - arr[i]) + frog(arr,i+1,i);
//             b =   Math.abs(arr[prev] - arr[i]) + frog(arr,i+2,i);
//
//     }
//
// return Math.min(a,b);
//
// }

 public static int vecation(int n, int prev, List<ArrayList<Integer>> l,int[][] dp){

     if(n == -1)
         return 0;
   if( dp[prev+1][n+1] > -1){
   return dp[prev+1][n+1];
   }
     int ans = 0;
     if(prev != 0){
        // System.out.println("used");
       ans = Math.max(ans,l.get(n).get(0) + vecation(n-1,0,l,dp));
     }

     if(prev != 1){
       ans = Math.max(ans,l.get(n).get(1) + vecation(n-1,1,l,dp));
     }

     if(prev != 2){
       ans = Math.max(ans,l.get(n).get(2) + vecation(n-1,2,l,dp));
     }

     return dp[prev+1][n+1] =  ans;

 }

    public static void main(String[] args) throws Exception {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//        int n = Integer.parseInt(br.readLine());
//        int[] arr = new int[n+1];
//        StringTokenizer str  = new StringTokenizer(br.readLine()," ");
//        int i = 0;
//        while(str.hasMoreTokens()){
//            arr[i] = Integer.parseInt(str.nextToken());
//            i++;
//        }
//
//           int[] dp = new int[arr.length];
//           Arrays.fill(dp,-1);
//

        int n = Integer.parseInt(br.readLine());
      int[][] dp = new int[n+1][n+1];
      for(int i = 0; i < dp.length; i++){
        Arrays.fill(dp[i],-1);

      }
        List<ArrayList<Integer>>  l = new ArrayList<>();

        for(int i = 0; i< n; i++){
            String str[] = br.readLine().split(" ");
            List<Integer> ll = new ArrayList<>();
            for(String k : str){

                ll.add(Integer.parseInt(k));

            }
            l.add(new ArrayList<>(ll));
            ll.clear();
        }
       // System.out.println(l);
            System.out.println(vecation(n-1,-1,l,dp));

     //   System.out.println(Arrays.toString(dp));
    }

}


import java.util.*;

class Main {
    public static int maxx(int a, int b, int c)
{
    return Math.max(Math.max(a,b),c);
}
    public static void main(String args[] ) throws Exception {
        Scanner ob=new Scanner(System.in);
        int n=ob.nextInt();
        int INF = (int)1e9+7;
        int a[]=new int[n];
        int dp[][]=new int[n][3];
        int a1,b,c;
        for(int i=0;i<n;i++)
        {
            a1=ob.nextInt();b=ob.nextInt();c=ob.nextInt();
            if(i==0)
            {
                dp[i][0]=a1;dp[i][1]=b;dp[i][2]=c;
            }
            else
            {
                dp[i][0]=Math.max(dp[i-1][1]+a1,dp[i-1][2]+a1);
                dp[i][1]=Math.max(dp[i-1][0]+b,dp[i-1][2]+b);
                dp[i][2]=Math.max(dp[i-1][1]+c,dp[i-1][0]+c);
            }
        }

        System.out.println(maxx(dp[n-1][0],dp[n-1][1],dp[n-1][2]));

        //System.out.println(Arrays.toString(a));
        //System.out.println(Arrays.toString(dp));

        //System.out.println(Arrays.toString(dp));
        //System.out.println("Hello World!");
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author vdewansa
 */
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);
        EKnapsack2 solver = new EKnapsack2();
        solver.solve(1, in, out);
        out.close();
    }

    static class EKnapsack2 {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int N = in.nextInt();
            int W = in.nextInt();
            int[] w = new int[N + 1];
            int[] v = new int[N + 1];
            for (int i = 1; i <= N; i++) {
                w[i] = in.nextInt();
                v[i] = in.nextInt();
            }

            EKnapsack2.Monotonic prev = new EKnapsack2.Monotonic(W);
            EKnapsack2.Monotonic next = new EKnapsack2.Monotonic(W);
            for (int i = 1; i <= N; i++) {
                for (long wPrev : prev.keys()) {
                    long vPrev = prev.get(wPrev);
                    next.update(wPrev, vPrev);
                    next.update(wPrev + w[i], vPrev + v[i]);
                }
                next.update(w[i], v[i]);
                prev = next;
                next = new EKnapsack2.Monotonic(W);
            }
            out.println(prev.get(W));
        }

        static class Monotonic {
            private final long kMin = 0;
            private final long kMax;
            private final long vMin = 0;
            private SortedMap<Long, Long> m = new TreeMap<>();

            public Monotonic(long kMax) {
                this.kMax = kMax;
            }

            public long get(long k) {
                if (m.containsKey(k)) {
                    return m.get(k);
                }
                SortedMap<Long, Long> head = m.headMap(k);
                if (head.isEmpty()) {
                    return vMin;
                }
                return head.lastKey();
            }

            public void update(long k, long v) {
                if (k < kMin || k > kMax) {
                    return;
                }
                long oldV = get(k);
                if (v > oldV) {
                    m.put(k, v);
                }
                for (long tailK : m.tailMap(k).keySet()) {
                    if (v > m.get(tailK)) {
                        m.put(tailK, v);
                    }
                }
            }

            public Set<Long> keys() {
                return m.keySet();
            }

        }

    }
}

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


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

 class Main{

    static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder("");
    static StringTokenizer stk = new StringTokenizer("");
    // static long[][] dp ;
    static Map<Integer,ArrayList<Integer>> adjList = new HashMap<>();
    static int N = 0;
    static int M = 0;
    static long maxValue = 0;

    public static  void main(String args[]){
        try{
            stk = new StringTokenizer(bf.readLine());
             N = Integer.parseInt(stk.nextToken());
             M = Integer.parseInt(stk.nextToken());
            //  dp =  new long[N+1][N+1];

            for(int i=0;i<M;i++){
                stk = new StringTokenizer(bf.readLine());
                int from = Integer.parseInt(stk.nextToken());
                int to = Integer.parseInt(stk.nextToken());

                if(adjList.containsKey(from)){
                    adjList.get(from).add(to);
                }else{
                    ArrayList<Integer> al = new ArrayList<>();
                    al.add(to);
                    adjList.put(from,al);
                }
            }

            solver();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void solver(){
        for(int i=1;i<=N;i++){
            dfs(i,i,1);
            // System.out.println("doing dfs from "+i+" value "+maxValue);
            // printMatrix()
        }
        System.out.println(maxValue);
    }

    public static void dfs(int src, int origin ,long length){
        if(adjList.get(src) == null || adjList.get(src).size() == 0){
            return ;
        }

        //check where things are starting
        for(int i=0;i < adjList.get(src).size();i++){
            // dp[src][adjList.get(src).get(i)] = Math.max(dp[src][adjList.get(src).get(i)],1);
            // dp[origin][adjList.get(src).get(i)] = Math.max(dp[origin][adjList.get(src).get(i)] , length );
            maxValue = Math.max(maxValue , length);
            dfs(adjList.get(src).get(i),origin,length+1);
        }
    }

}

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

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

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

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

Sample Output 3

3

The red directed path in the following figure is one of the longest:


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

class Main{
	static int[] dp;
	static LinkedList<Integer>[] graph;
	static int rec(int v) {
		if(dp[v] != -1) return dp[v];

		int ret = 0;
		for(int u : graph[v]) {
			ret = Math.max(ret, rec(u) + 1);
		}
		return dp[v] = ret;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			int N = sc.nextInt(), M = sc.nextInt();
			graph = new LinkedList[N];
			for(int i = 0; i < N; i++) graph[i] = new LinkedList<Integer>();
			for(int i = 0; i < M; i++) {
				int x = sc.nextInt(), y = sc.nextInt();
				graph[x - 1].add(y - 1);
			}
			dp = new int[N];
			Arrays.fill(dp, -1);
			int ans = 0;
			for(int i = 0; i < N; i++) ans = Math.max(ans, rec(i));
			System.out.println(ans);
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String args[]) {
 		Scanner scan = new Scanner(System.in);
      	int rows = scan.nextInt();
      	int cols = scan.nextInt();
        scan.nextLine();
      	boolean[][] grid = new boolean[rows][cols];
      	for(int r = 0; r < rows; r++){
          	char[] line = scan.nextLine().toCharArray();
        	for(int c = 0; c < cols; c++){
            	char cell = line[c];
              	grid[r][c] = cell == '.';
            }
        }
      	scan.close();
      	Solver solver = new Solver(grid);
      	System.out.println(solver.solve());
	}

  public static class Solver{
    private int mod = 1_000_000_007;
 	private boolean[][] grid;

    public Solver(boolean[][] grid){
    	this.grid = grid;
    }

    public int solve()
    {
      int rows = grid.length;
      int cols = grid[0].length;

      int[][] dp = new int[rows][cols];
	  fillFirstRow(dp, cols);
      fillFirstCol(dp, rows);

      for(int r = 1; r < rows; r++){
      	for(int c = 1; c < cols; c++){
          if(!grid[r][c]) dp[r][c] = 0;
          else{
            dp[r][c] = (dp[r-1][c] + dp[r][c-1])%mod;
          }
        }
      }
      return dp[rows-1][cols-1];
    }
    private void fillFirstRow(int[][] dp, int cols){
      int c = 0;
      for(; c < cols; c++){
        if(grid[0][c]){
          dp[0][c] = 1;
        }else break;
      }
      for(; c < cols; c++) dp[0][c] = 0;
    }
    private void fillFirstCol(int[][] dp, int rows){
      int r = 0;
      for(; r < rows; r++){
        if(grid[r][0]){
          dp[r][0] = 1;
        }else break;
      }
      for(; r < rows; r++) dp[r][0] = 0;
    }
  }
}

Score : 100 points

Problem Statement

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

For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}.
If a_{i, j} is ., Square (i, j) is an empty square; if a_{i, j} is #, Square (i, j) is a wall square.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

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

Find the number of Taro's paths from Square (1, 1) to (H, W).
As the answer can be extremely large, find the count modulo 10^9 + 7.

Constraints

H and W are integers.

2 \leq H, W \leq 1000

a_{i, j} is . or #.

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

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W}

Output

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

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5
..#..
.....
#...#
.....
..#..

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

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


/*input
5
0.42 0.01 0.42 0.99 0.42
*/
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author masterbios
 */
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);
        CLinovaAndKingdom solver = new CLinovaAndKingdom();
        solver.solve(1, in, out);
        out.close();
    }

    static class CLinovaAndKingdom {

        final int MAXN = (int) (1e3) + 10;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            double p[] = new double[n];
            double dp[][] = new double[n + 3][n + 3];
            for (int i = 0; i < n; i++) p[i] = in.nextDouble();
            dp[0][0] = 1;
            for (int i = 1; i <= n; i++) {
                for (int j = 0; j <= i; j++) {
                    if (j == 0) {
                        dp[i][j] = (1 - p[i - 1]) * dp[i - 1][j];
                    } else {
                        dp[i][j] = p[i - 1] * dp[i - 1][j - 1];
                        dp[i][j] += (1 - p[i - 1]) * dp[i - 1][j];
                    }
                }
            }
            double res = 0.0d;
            for (int i = (n + 1) / 2; i <= n; i++) {
                res += dp[n][i];
            }
            out.printf("%.14f\n", res);

        }

        // public double solve(int coins, int heads) {
        //     if (coins == 0) {
        //         // return 1.0d;
        //         if (heads == 0) return 1.0d;
        //         else return 0.0d;
        //     }
        //     if (heads < 0) { System.err.println("reach"); return 0.0d; }
        //     if (dp[coins][heads] != 0.0d) return dp[coins][heads];
        //     double ans = p[coins - 1] * solve(coins - 1, heads - 1);
        //     ans += (1.0d - p[coins - 1]) * solve(coins - 1, heads);
        //     return dp[coins][heads] = ans;
        // }

        public int max(int ...a) {
            int max = Integer.MIN_VALUE;
            for (int i : a) max = Math.max(max, i);
            return max;
        }

        public int min(int ...a) {
            int min = Integer.MAX_VALUE;
            for (int i : a) min = Math.min(min, i);
            return min;
        }

        public long max(long ...a) {
            long max = Long.MIN_VALUE;
            for (long i : a) max = Math.max(max, i);
            return max;
        }

        public long min(long ...a) {
            long min = Long.MAX_VALUE;
            for (long i : a) min = Math.min(min, i);
            return min;
        }

    }

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

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

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

    }
}

Score : 100 points

Problem Statement

Let N be a positive odd number.

There are N coins, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.

Taro has tossed all the N coins.
Find the probability of having more heads than tails.

Constraints

N is an odd number.

1 \leq N \leq 2999

p_i is a real number and has two decimal places.

0 < p_i < 1

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 \ldots p_N

Output

Print the probability of having more heads than tails.
The output is considered correct when the absolute error is not greater than 10^{-9}.

Sample Input 1

3
0.30 0.60 0.80

Sample Output 1

0.612

The probability of each case where we have more heads than tails is as follows:

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Head) is 0.3 × 0.6 × 0.8 = 0.144;

The probability of having (Coin 1, Coin 2, Coin 3) = (Tail, Head, Head) is 0.7 × 0.6 × 0.8 = 0.336;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Tail, Head) is 0.3 × 0.4 × 0.8 = 0.096;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Tail) is 0.3 × 0.6 × 0.2 = 0.036.

Thus, the probability of having more heads than tails is 0.144 + 0.336 + 0.096 + 0.036 = 0.612.

Sample Input 2

1
0.50

Sample Output 2

0.5

Outputs such as 0.500, 0.500000001 and 0.499999999 are also considered correct.

Sample Input 3

5
0.42 0.01 0.42 0.99 0.42

Sample Output 3

0.3821815872


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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in[] = br.readLine().split(" ");
        int n = Integer.parseInt(in[0]);
        in = br.readLine().split(" ");
        double arr[]=new double[n];
        double dp[] = new double[n+1];
        for(int i=0;i<n;i++){
            arr[i]=Double.parseDouble(in[i]);
        }
        dp[0]=1;
        for(int i=0;i<n;i++){
            for(int coin=i+1;coin>=0;coin--){
                dp[coin]= ((coin==0)?0:dp[coin-1]*arr[i])+dp[coin]*(1-arr[i]);
            }
        }
        double ans = 0;
        for(int i=0;i<=n;i++){
            int tail = n-i;
            if(tail<i){
                ans+=dp[i];
            }
        }

        System.out.println(ans);
    }
}


import java.util.*;

public class Main
{
	public static void main(String [] Args)
	{
		Scanner in = new Scanner(System.in);
		int n=in.nextInt();
		double [][] dp=new double [n+1][n];
		double [] p=new double [n];
		for(int i=0;i<n;i++)
		{
			p[i]=in.nextDouble();
		}
		dp[0][0]=1.0d-p[0];
		dp[1][0]=p[0];
		for(int i=1;i<n;i++)
		{
			dp[0][i]=dp[0][i-1]*(1.0000000000d-p[i]);
		}
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<n;j++)
			{
				dp[i][j]=dp[i-1][j-1]*p[j]+dp[i][j-1]*(1.0000000000d-p[j]);
			}
		}
		Double ans=0.0;
		for(int i=n/2+1;i<=n;i++)
		{
			ans=ans+dp[i][n-1];
		}
		System.out.println(ans);
	}
}


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

    static class KStones {
        public void solve(int testNumber, inputClass sc, PrintWriter out) {
            int n = sc.nextInt();
            int k = sc.nextInt();
            int[] tab = new int[n];
            boolean[] dp = new boolean[k + 1];

            for (int i = 0; i < n; i++) {
                tab[i] = sc.nextInt();
            }

            for (int i = 0; i < k + 1; i++) {
                if (!dp[i]) {
                    for (int j = 0; j < n; j++) {
                        if (i + tab[j] < k + 1) {
                            dp[i + tab[j]] = true;
                        }
                    }
                }
            }

            if (dp[k]) {
                out.println("First");
            } else {
                out.println("Second");
            }
        }

    }

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

    }
}

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second


import java.util.*;
import java.io.*;
public class Main {

    public static long sum(int[] arr, int i, int j) {
        int sum = 0;
        for(int k = i; k <= j; k++){
            sum += arr[k];

        }
        return sum;
    }

    static long solve(int[] arr, int i, int j,long[][] dp){
        if(i== j)
            return 0;
        if(dp[i][j] != -1)
            return dp[i][j];

        long ans = Long.MAX_VALUE;

        for(int k = i; k < j; k++){
          ans =  Math.min(ans, solve(arr,i,k,dp) + solve(arr, k+1, j,dp) + sum(arr,i,j));
        }

        return  dp[i][j] = ans;

    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer token;
        int n = Integer.parseInt(br.readLine().trim());
        int[] arr = new int[n];
        token = new StringTokenizer(br.readLine().trim()," ");
        for(int i = 0; i < arr.length; i++){
            arr[i] = Integer.parseInt(token.nextToken());
        }

        long[][] dp = new long[arr.length][arr.length];
       for(int i = 0; i < dp.length; i++)
           Arrays.fill(dp[i],-1);

       System.out.println(solve(arr, 0, arr.length-1,dp));
    }
}

Score : 100 points

Problem Statement

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

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

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

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

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

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

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

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

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

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

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

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

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

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

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

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

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

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

(13, 16) → (29)


import java.io.*;
import java.util.*;
public class Main {

    static long MOD = 1000*1000*1000 + 7;
    public static void main(String args[]) {
        int n = 0;
        int[] h = null;
        int[] a = null;
        try (Scanner scanner = new Scanner(System.in)) {
            n = scanner.nextInt();
            h = new int[n];
            a = new int[n];
            for(int i = 0; i < n; i++) {
                h[i] = scanner.nextInt();
            }
            for(int i = 0; i < n; i++) {
                a[i] = scanner.nextInt();
            }
        }

        //dp[i] = max possible beauty for height i;
        long[] dp = new long[n+1];
        long ret = 0;
        for(int flower = 0; flower < n ; flower++) {
            for(int he = 0; he < h[flower]; he++) {
                dp[h[flower]] = Math.max(dp[h[flower]], dp[he] + a[flower]);
                ret = Math.max(ret, dp[h[flower]]);
            }
        }

        System.out.println(ret);
    }

}

Score : 100 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

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

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

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

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

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

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

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

Sample Input 4

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

Sample Output 4

31

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


import java.util.*;
import java.math.*;
import java.lang.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int n = sc.nextInt();
		int h = sc.nextInt();
		int w = sc.nextInt();
		int result = 0;

		for(int i=0;i<n;i++){
			int a = sc.nextInt();
			int b = sc.nextInt();

			if(a <h || b < w){
				continue;
			}
			// System.out.println(a/h);
			// System.out.println(b/w);
			result += Math.min(a/h,b/w);
		}

		System.out.println(result);
	}

}

Score : 200 points

Problem Statement

There are N rectangular plate materials made of special metal called AtCoder Alloy.
The dimensions of the i-th material are A_i \times B_i (A_i vertically and B_i horizontally).

Takahashi wants a rectangular plate made of AtCoder Alloy whose dimensions are exactly H \times W.
He is trying to obtain such a plate by choosing one of the N materials and cutting it if necessary.
When cutting a material, the cuts must be parallel to one of the sides of the material.
Also, the materials have fixed directions and cannot be rotated.
For example, a 5 \times 3 material cannot be used as a 3 \times 5 plate.

Out of the N materials, how many can produce an H \times W plate if properly cut?

Constraints

1 \leq N \leq 1000

1 \leq H \leq 10^9

1 \leq W \leq 10^9

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N H W
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

3 5 2
10 3
5 2
2 5

Sample Output 1

2

Takahashi wants a 5 \times 2 plate.

The dimensions of the first material are 10 \times 3. We can obtain a 5 \times 2 plate by properly cutting it.

The dimensions of the second material are 5 \times 2. We can obtain a 5 \times 2 plate without cutting it.

The dimensions of the third material are 2 \times 5. We cannot obtain a 5 \times 2 plate, whatever cuts are made. Note that the material cannot be rotated and used as a 5 \times 2 plate.

Sample Input 2

10 587586158 185430194
894597290 708587790
680395892 306946994
590262034 785368612
922328576 106880540
847058850 326169610
936315062 193149191
702035777 223363392
11672949 146832978
779291680 334178158
615808191 701464268

Sample Output 2

8


import java.util.Scanner;

public class Main {
	static Scanner sc = new Scanner(System.in);
	static int N = sc.nextInt();
	static int H = sc.nextInt();
	static int W = sc.nextInt();
	static int[] a = new int[N];
	static int[] b = new int[N];
	public static void main(String[] args) {
		for (int i = 0; i < N; i++) {
			a[i] = sc.nextInt();
			b[i] = sc.nextInt();
		}
		int ans = 0;
		for (int i = 0; i < N; i++) {
			if (a[i] >= H && b[i] >=W) {
				ans++;
			}
		}
		System.out.println(ans);
	}
}