//Coded By Visnunathan

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

public class Main {
    public static void main(String[] args) {
        FastScanner sc=new FastScanner();
        char[] line = sc.next().toCharArray();
        int sum = 0;
        for (char c:line) sum+=c-'0';
        System.out.println(sum%9==0?"YES":"NO");
    }
    // public static void main(String[] args) {
    //     FastScanner fs=new FastScanner();
    //     char[] line=fs.next().toCharArray();
    //     int sum=0;
    //     for (char c:line) sum+=c-'0';
    //     System.out.println(sum%9==0?"Yes":"No");
    // }

    static final Random random=new Random();

    static void ruffleSort(int[] a) {
        int n=a.length;//shuffle, then sort
        for (int i=0; i<n; i++) {
            int oi=random.nextInt(n), temp=a[oi];
            a[oi]=a[i]; a[i]=temp;
        }
        Arrays.sort(a);
    }

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

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }
    }

}

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


import java.util.*;

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

    int sum = 0;
    for(int i = 0; i < n.length();i++){
      sum += (int)n.charAt(i);
    }

    if(n.equals("0")){
      System.out.println("Yes");
      return;
    }

    if(sum % 9 == 0){
      System.out.println("Yes");
    }else{
      System.out.println("No");
    }
  }
}

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

Submitted source-code file size, in bytes.

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

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


import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	public static void main(final String[] args) {
		Scanner sc = new Scanner(System.in);
		BigInteger n = sc.nextBigInteger();
		sc.close();
		prtln(n.remainder(new BigInteger("9")).equals(new BigInteger("0")) ? "Yes" : "No");
	}

	public static <T> void prtln(T t) { System.out.println(t); }
}


import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
        int maxA = sc.nextInt();
        long res = 0;
        for(int i=1; i<N; i++){
            int A = sc.nextInt();
            maxA = Math.max(maxA,A);
            res = res + maxA - A;

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

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
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 lucasr
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        MyScanner in = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        FBraveCHAIN solver = new FBraveCHAIN();
        solver.solve(1, in, out);
        out.close();
    }

    static class FBraveCHAIN {
        static int N;
        static int[][] table;
        static int[] first;
        static int[] second;
        static int[] third;
        static int[][] vals;
        static int[][] fulls;

        public void solve(int testNumber, MyScanner sc, PrintWriter out) {
            N = sc.nextInt();
            table = new int[N + 1][N + 1];
            for (int i = 0; i < N + 1; i++) {
                Arrays.fill(table[i], -1);
            }
            first = new int[N];
            Arrays.fill(first, -1);
            second = new int[N];
            Arrays.fill(second, -1);
            third = new int[N];
            Arrays.fill(third, -1);
            vals = new int[N + 1][];
            for (int i = 0; i <= N; i++) {
                int tot = 3;
                if (i == 0) tot = 2;
                else if (i == N) tot = 1;
                vals[i] = new int[tot];
                for (int j = 0; j < tot; j++) {
                    int vv = sc.nextInt() - 1;
                    vals[i][j] = vv;
                    if (first[vv] == -1) {
                        first[vv] = i;
                    } else if (second[vv] == -1) {
                        second[vv] = i;
                    } else {
                        third[vv] = i;
                    }
                }
            }

            fulls = new int[N + 1][N + 2];
            for (int i = 0; i < N + 1; i++) {
                for (int j = i + 1; j < N + 2; j++) {
                    fulls[i][j] = fulls[i][j - 1] + full(j - 1);
                }
            }
            out.println(calc(N, N));
        }

        static int full(int index) {
            if (0 < index && index < N) {
                if (vals[index][0] == vals[index][1] && vals[index][1] == vals[index][2]) return 1;
            }
            return 0;
        }

        static int calc(int usedFrom, int upTo) {
            if (usedFrom >= upTo) usedFrom = N;
            int ret = table[usedFrom][upTo];
            if (ret != -1) return ret;
            ret = 0;
            if (upTo > 0) {
                ret = calc(usedFrom, upTo - 1);
                for (int i = 0; i < vals[upTo].length; i++) {
                    int cur = vals[upTo][i];
                    if (third[cur] == upTo) {
                        int[] tmp = new int[3];
                        int leftNeed = 0;
                        if (first[cur] < upTo) tmp[leftNeed++] = first[cur];
                        if (second[cur] < upTo) tmp[leftNeed++] = second[cur];
                        if (usedFrom < upTo) tmp[leftNeed++] = usedFrom;
                        if (leftNeed <= 2) {
                            Arrays.sort(tmp, 0, leftNeed);
                            if (leftNeed == 2) {
                                int next = tmp[1];
                                ret = Math.max(ret, fulls[next + 1][upTo] + 1 + calc(tmp[0], next));
                            } else if (leftNeed == 1) {
                                ret = Math.max(ret, 1 + calc(tmp[0], upTo - 1));
                            } else {
                                ret = Math.max(ret, 1 + calc(N, upTo - 1));
                            }
                        }
                    }
                }
            }
            return table[usedFrom][upTo] = ret;
        }

    }

    static class MyScanner {
        private BufferedReader br;
        private StringTokenizer tokenizer;

        public MyScanner(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

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

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

    }
}

Score : 600 points

Problem Statement

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be 2\ 2\ 2\ 1\ 1\ 1 from left to right.

Then, remove the three leftmost cards, all of which have the same integer 2, gaining 1 point.

Now, the integers written on the remaining cards are 1\ 1\ 1.

Since these three cards have the same integer 1, we gain 1 more point.

In this way, we can gain 2 points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3


import java.util.Scanner;

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

      	if (rain.contains("R")) {
          System.out.println(1);
        } else if(rain.contains("RR")) {
		  System.out.println(2);
        } else if(rain.contains("RRR")) {
	      System.out.println(3);
        } else {
          System.out.println(0);
        }
		sc.close();
	}

}

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


import java.util.Scanner;

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

    private static void test_mine(){
        Scanner scan = new Scanner(System.in);
        String s = scan.next();

        int count = 0;
        if(s.charAt(1) == 'S'){
            if(s.charAt(0) == 'R' || s.charAt(2) == 'R')
                count = 1;
            else
                count = 0;
        }else{
            if(s.charAt(0) == 'R'){
                if(s.charAt(2) == 'R'){
                    count = 3;
                }else{
                    count = 2;
                }
            }else if(s.charAt(2) == 'R'){
                if(s.charAt(0) == 'R'){
                    count = 3;
                }else{
                    count = 2;
                }
            }else
                count = 1;
            }
        System.out.println(count);
    }

    private static void test_ans(){
        Scanner scan = new Scanner(System.in);
        String s = scan.next();

        boolean p = s.charAt(0) == 'R';
        boolean q = s.charAt(1) == 'R';
        boolean r = s.charAt(2) == 'R';

        int count = 0;
        if(p && q && r)
            count = 3;
        else if((p && q) || (q && r))
            count = 2;
        else if(p || q || r)
            count = 1;
        else
            count = 0;

        System.out.println(count);
    }
}


import java.util.*;

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

                int result=0;
                boolean flag = false;
                for(int i = 0; i < 3; i++){
                        if(str.charAt(i) == 'R'){
                                result++;
                                flag = true;
                        }
                        else{
                                if(flag == true) break;
                        }
                }

                System.out.println(result);
        }
}


import java.util.*;

public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    long array[] = new long[num];
    for(int i = 0;i < num;i++){
      array[i] = sc.nextLong();
    }
    long count = 0;
    for(int i = 0;i < num - 2;i++){
      for(int j = i + 1;j < num - 1;j++){
        for(int k = j + 1;k < num;k++){
          long a = array[i];
          long b = array[j];
          long c = array[k];
          long sum = a + b + c;
          if(a != b && b != c && c != a){
            long max = Math.max(a,Math.max(b,c));
            if(max < sum - max){
              count++;
            }
          }
        }
      }
    }
    System.out.println(count);
  }
}

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


import javax.swing.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;

public class Main {
  static class Pair {
    int num;
    int cut;

    Pair(int num, int cut) {
      this.num = num;
      this.cut = cut;
    }

    double getVal() {
      return -num / (double) cut;
    }
  }

  public static void main(String[] args) throws IOException {
    sc = new MScanner(System.in);
    pw = new PrintWriter(System.out);
    long X = sc.nextLong();
    long K = sc.nextLong();
    long D = sc.nextLong();
    long res = solve(X,D, K);
    if(X < 0) {
        if( X + D * K < 0) {
          pw.println(- (X + D * K));
        } else {
          pw.println(Math.min(res, Math.abs(res - 2 * D)));
        }
        pw.flush();
        return;
    }
    pw.println(res);

    //pw.println("end");
    // pw.println();

    pw.flush();
    // System.out.println(cnt);
  }
  static long solve(long X, long D,long K) {
    if (K  < X/D) {
      return (X - K * D);
    }
    long multiple = Math.floorDiv(X, D);
    long res = X - D * multiple;
    if (((K - multiple) & 1) == 0) {
      return (Math.min(res, Math.abs(res - 2 * D)));
    } else {
      return (Math.min(Math.abs(res - D), Math.abs(res + D)));
    }
  }

  /**
   * https://www.slideshare.net/hcpc_hokudai/binary-indexed-tree A space efficient version segment
   * tree. Usually for range sum. Or the required metric can be calulated in that:
   *
   *
right_metric = parant_metric - left_metric Only then, we can stop memoizing right_metric
   *
   *
The internal structure is a 1-base array, to simplify calculation of parent node's idx. lsb
   * = 3 & -3 = 2 (0x0011 & 0x1101 = 0x0001) lastParentOf3 = 3 - lsb = 2 curParentOf3 = 3 + lsb = 4
   */
  static class FenwickTree {
    private final long[] state;
    private final int size;

    FenwickTree(int size) {
      this.size = size;
      state = new long[size + 1];
    }

    @Override
    public String toString() {
      return Arrays.toString(state);
    }

    long queryRangeSumFromZeroTo(int idx) {
      long sum = 0;
      while (idx != 0) {
        sum += state[idx];
        idx -= (idx & -idx);
      }
      return sum;
    }

    /** @param val can be negative */
    void updateElement(int idx, long val) {
      while (idx <= size) {
        state[idx] += val;
        idx += (idx & -idx);
      }
    }
  }

  // sc.close();
  // pw.println(cnt);
  // pw.flush();

  static PrintWriter pw;
  static MScanner sc;

  static class MScanner {
    StringTokenizer st;
    BufferedReader br;

    public MScanner(InputStream system) {
      br = new BufferedReader(new InputStreamReader(system));
    }

    public MScanner(String file) throws Exception {
      br = new BufferedReader(new FileReader(file));
    }

    public String next() throws IOException {
      while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
      return st.nextToken();
    }

    public int[] intArr(int n) throws IOException {
      int[] in = new int[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      return in;
    }

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

    public int[] intSortedArr(int n) throws IOException {
      int[] in = new int[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      shuffle(in);
      Arrays.sort(in);
      return in;
    }

    public long[] longSortedArr(int n) throws IOException {
      long[] in = new long[n];
      for (int i = 0; i < n; i++) in[i] = nextLong();
      shuffle(in);
      Arrays.sort(in);
      return in;
    }

    public Integer[] IntegerArr(int n) throws IOException {
      Integer[] in = new Integer[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      return in;
    }

    public Long[] LongArr(int n) throws IOException {
      Long[] in = new Long[n];
      for (int i = 0; i < n; i++) in[i] = nextLong();
      return in;
    }

    public String nextLine() throws IOException {
      return br.readLine();
    }

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

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

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

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

    public boolean ready() throws IOException {
      return br.ready();
    }

    public void waitForInput() throws InterruptedException {
      Thread.sleep(3000);
    }
  }

  static void shuffle(int[] in) {
    for (int i = 0; i < in.length; i++) {
      int idx = (int) (Math.random() * in.length);
      int tmp = in[i];
      in[i] = in[idx];
      in[idx] = tmp;
    }
  }

  static void shuffle(long[] in) {
    for (int i = 0; i < in.length; i++) {
      int idx = (int) (Math.random() * in.length);
      long tmp = in[i];
      in[i] = in[idx];
      in[idx] = tmp;
    }
  }
}

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


import java.util.*;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        long x=sc.nextLong();
        long k=sc.nextLong();
        long d=sc.nextLong();
        if(x==k && k==d)
        {
        	System.out.println(x);

            System.exit(1);
        }
        x=Math.abs(x);
        k=k-(x/d);
        x=x%d;
        if(k<=0)
        {
        	System.out.println((x-(k*d)));
        	System.exit(1);
        }
        else
        {
        	if(k%2==1)
        		System.out.println(Math.abs(x-d));
        	else
        		System.out.println(x);
        }

	}

}


import java.util.Scanner;

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

		Scanner sc = new Scanner(System.in);
		long x = sc.nextLong();
		long k = sc.nextLong();
		long d = sc.nextLong();
		long min1 = x % d;
		if(min1 < 0)
			min1 += d;
		long min2 = min1 - d;
		long ans = Long.MAX_VALUE / 2;
		if(Math.abs(x - min1) / d <= k && Math.abs(x - min1) / d % 2 == k % 2) {
			ans = min1;
		}
		if(Math.abs(x - min2) / d <= k && Math.abs(x - min2) / d % 2 == k % 2) {
			ans = Math.abs(min2);
		}

		ans = Math.min(ans, Math.abs(x - k * d));

		sc.close();
		System.out.println(ans);

	}
}


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

public class Main {

    void solve() throws IOException {
        int N = ni();
        int K = ni();
        int[] P = new int[N];
        int[] C = new int[N];
        for (int i = 0; i < N; i++) {
            P[i] = ni()-1;
        }
        for (int i = 0; i < N; i++) {
            C[i] = ni();
        }
        long ans = -Long.MAX_VALUE;
        for (int i = 0; i < N; i++) {
            HashSet<Integer> visited = new HashSet<>();
            int current = i;
            int count = 0;
            long cost = 0;
            while(true){
                visited.add(current);
                count++;
                current = P[current];
                cost += C[current];
                ans = Math.max(ans, cost);
                // System.out.println(current);
                // System.out.println(cost);
                if(visited.contains(current) || count>=K) break;
            }
            if(count < K){
                if(cost>0)cost += cost * ((K-count)/count);
                ans = Math.max(ans, cost);
                // System.out.println(cost);
                int rest = K%count;
                for (int j = 0; j < rest; j++) {
                    current = P[current];
                    cost += C[current];
                    ans = Math.max(ans, cost);
                    // System.out.println(cost);
                }
            }
            // System.out.println();

        }

        out.println(ans);
    }

    final int mod = 1000000007;
    final BigInteger MOD = BigInteger.valueOf(mod);
    int upperBound(ArrayList<Long> list, Long target){
        int i = Collections.binarySearch(list, target, new UpperBoundComparator<Long>());
        return ~i;
    }
    class UpperBoundComparator<T extends Comparable<? super T>> implements Comparator<T>{
        public int compare(T x, T y){
            return (x.compareTo(y) > 0) ? 1 : -1;
        }
    }
    int lowerBound(ArrayList<Long> list, Long target){
        int i = Collections.binarySearch(list, target, new LowerBoundComparator<Long>());
        return ~i;
    }
    class LowerBoundComparator<T extends Comparable<? super T>> implements Comparator<T>{
        public int compare(T x, T y){
            return (x.compareTo(y) >= 0) ? 1 : -1;
        }
    }
    int mul(int x, int y){
        int val = (int)((x * 1L * y) % mod);
        return val>=0 ? val : val+mod;
    }
    int add(int x, int y) {
        x += y;
        if(x < 0) x += mod;
        if(x>=mod) x -= mod;
        return x;
    }
    int sub(int x, int y){
        x = add(x,mod-y);
        if(x < 0) x += mod;
        if(x>=mod) x -= mod;
        return x;
    }
    String ns() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine(), " ");
        }
        return tok.nextToken();
    }

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

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

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

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

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

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

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

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

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

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

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.LongStream;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.OptionalLong;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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;
        MyScanner in = new MyScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        D solver = new D();
        solver.solve(1, in, out);
        out.close();
    }

    static class D {
        long minValue = (long) -1e50;

        public void solve(int testNumber, MyScanner in, PrintWriter out) {
            int N = in.Int();
            int K = in.Int();
            int[] P = new int[N];
            for (int i = 0; i < N; i++) {
                P[i] = in.Int() - 1;
            }
            int[] C = in.Int(N);

            long ans = minValue;
            boolean[] f = new boolean[N];
            for (int n = 0; n < N; n++) {
                if (f[n]) continue;
                Set<Integer> set = new HashSet<>();
                int cur = n;
                long sum = 0;
                while (!set.contains(cur)) {
                    f[cur] = true;
                    set.add(cur);
                    cur = P[cur];
                    sum += C[cur];
                }
                int k = K % set.size();
                long[] c = new long[N];
                long max = minValue;
                long max2 = 0;
                for (int i = 0; i < set.size(); i++) {
                    if (i <= k) max2 = Math.max(max2, max);
                    long[] cc = new long[N];
                    for (int j : set) {
                        cc[P[j]] = c[j] + C[j];
                    }
                    c = cc;
                    max = Math.max(max, LongStream.of(c).max().getAsLong());
                }
                ans = Math.max(ans, Math.max(max, sum * (K / set.size()) + max2));
            }
            out.println(ans);
        }

    }

    static class MyScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public MyScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

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

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

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

    }
}


import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
// import java.io.BufferedReader;
// import java.io.IOException;
// import java.io.InputStreamReader;
// import java.util.ArrayList;
// import java.util.Arrays;
// import java.util.Collections;
// import java.util.List;
// import java.util.HashSet;
// import java.util.Set;
// import java.util.Map;
// import java.util.HashMap;

import java.math.*;

public class Main {
    private static Scanner sc;
    private static final long mod = 1000000007;

    public static void main(final String[] args) {
        final Main instance = new Main();
        sc = instance.new Scanner();
        instance.solve();
    }

    private static String getUpperAlpha(int i) {
        return String.valueOf((char) (i + 64));
    }

    /* i=1 return a */
    private static String getLowerAlpha(int i) {
        return String.valueOf((char) (i + 96));
    }

    private class Scanner {
        String[] s;
        int i;
        BufferedReader br;
        String regex = " ";

        public Scanner() {
            s = new String[0];
            i = 0;
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        @Override
        protected void finalize() throws Throwable {
            try {
                super.finalize();
            } finally {
                destruction();
            }
        }

        private void destruction() throws IOException {
            if (br != null)
                br.close();
        }

        public String next() throws IOException {
            if (i < s.length)
                return s[i++];
            String st = br.readLine();
            while (st == "")
                st = br.readLine();
            s = st.split(regex, 0);
            i = 0;
            return s[i++];
        }

        public int nextInt() throws NumberFormatException, IOException {
            return Integer.parseInt(next());
        }

        public Long nextLong() throws NumberFormatException, IOException {
            return Long.parseLong(next());
        }

        public Double nextDouble() throws NumberFormatException, IOException {
            return Double.parseDouble(next());
        }

        public long[] nextLongArray(int n) throws NumberFormatException, IOException {
            long[] ret = new long[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextLong();
            }
            return ret;
        }

        public int[] nextIntArray(int n) throws NumberFormatException, IOException {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }
    }

    private void solve() {
        try {
            int n = sc.nextInt();
            long k = sc.nextLong();
            int[] p = sc.nextIntArray(n);
            long[] c = sc.nextLongArray(n);
            long ans = 0;

            long max = Long.MIN_VALUE;
            int loop = 0;
            for (int i = 0; i < n; i++) {
                long sum = 0;
                int idx = i;
                int iniIdx = i;
                loop = 0;
                for (int j = 0; j < k; j++) {
                    int loopcount = 0;
                    sum += c[idx];
                    idx = p[idx] - 1;

                    if (iniIdx == idx) {
                        if (sum > max) {
                            max = sum;
                            loopcount++;
                            loop = loopcount;
                        }
                        break;
                    } else {
                        max = Math.max(max, sum);
                    }
                    loopcount++;
                }
            }
            if (loop != 0)
                ans = max * (k / loop);

            max = Long.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                long sum = 0;
                int idx = i;
                for (int j = 0; j < k; j++) {
                    sum += c[idx];
                    idx = p[idx] - 1;
                    max = Math.max(max, sum);
                }
            }

            // if (k > n) {
            // long sum = 0;
            // for (int i = 0; i < n; i++) {
            // sum += c[i];
            // }
            // if (sum > 0) {
            // ans = sum * (k / n);
            // }
            // k %= n;
            // }
            // System.out.println(ans);

            System.out.println(max + ans);
        } catch (

        Exception e) {
            e.printStackTrace();
        }

    }
}


import java.util.*;
public class Main{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                int n = sc.nextInt();
                double[] a = new double[n];
                for(int i = 0 ; i < n ; i++){
                        a[i] = sc.nextDouble();
                }
                int yono = 0;
                sc.close();
                for(int i = 0 ; i < n ; i++){
                        for(int j = 0 ; j < i ; j++){
                                if(a[i] * a[j] % 1 == 0) yono++;
                        }
                }
                System.out.println(yono);
        }
}//0=48
 //a=97 a -> +26 = 123
//鶏になれ

Score : 300 points

Problem Statement

You are given N real values A_1, A_2, \ldots, A_N.
Compute the number of pairs of indices (i, j)
such that i < j and the product A_i \cdot A_j is integer.

Constraints

2 \leq N \leq 200\,000

0 < A_i < 10^4

A_i is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

N
A_1
A_2
\vdots
A_N

Output

Print the number of pairs with integer product A_i \cdot A_j (and i < j).

Sample Input 1

5
7.5
2.4
17.000000001
17
16.000000000

Sample Output 1

3

There are 3 pairs with integer product:

7.5 \cdot 2.4 = 18

7.5 \cdot 16 = 120

17 \cdot 16 = 272

Sample Input 2

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Sample Output 2

8


import java.util.*;
public class Main{
	public static void main(String args[]){
    	Scanner s=new Scanner(System.in);
      	int n=s.nextInt();
      	if(n>=30){
          System.out.println("Yes");
        }else{
        	System.out.println("No");
        }
    }
}

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


import java.util.*;

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

    if(x >= 30){
      System.out.println("Yes");
    }else{
      System.out.println("No");
    }
    scanner.close();
    return;
  }

}


public class Main {
	public static void main(String[] args) {
		var sc = new java.util.Scanner(System.in);
		var n = sc.nextInt();
		var d = sc.nextLong();
		var cnt = 0;
		for(int i=0;i<n;i++) {
			var p = sc.nextLong();
			var q = sc.nextLong();
			if(Math.sqrt(p*p+q*q)<=d) {
				cnt++;
			}
		}
		System.out.println(cnt);
	}
}

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


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

public class Main {
	static final int INF = (int) (1e9 + 10);
	static final long MOD = (int) (1e9 + 7);
	static final int N = (int) (4e5 + 5);
	// static ArrayList<Integer>[] graph;
	// static boolean visited[];
	// static long size[];

	public static void main(String[] args) throws NumberFormatException, IOException {
		FastReader sc = new FastReader();
		PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		// Scanner scn = new Scanner(System.in);
		//
		int n = sc.nextInt();
		int val = 7 % n;
		int ans = -1;
		for (int i = 1; i <= 1e7; i++) {
			if (val == 0) {
				ans = i;
				break;
			} else {
				val = (val * 10 + 7) % n;
			}
		}
		pr.println(ans);
		//
		// Coded to Perfection by Rohan Mukhija
		pr.flush();
		pr.close();
	}

	/*
	 * Template From Here
	 */
	private static boolean possible(long[] arr, double mid, long k) {
		long c = 0;
		for (int i = 0; i < arr.length; i++) {
			c += ((arr[i]) / mid);
			if (c % arr[i] == 0)
				c--;
		}
		// System.out.println(mid+" "+c+" "+k);
		if (c <= k)
			return true;
		return false;
	}

	public static class Pair implements Comparable<Pair> {
		int u;
		int v;

		Pair(int u, int v, char c) {
			this.u = u;
			this.v = v;

		}

		public int compareTo(Pair compareEdge) {
			return Long.compare(this.v, compareEdge.v);
		}
	};

	static void sort(long[] a) {
		ArrayList<Long> l = new ArrayList<>();
		for (long i : a)
			l.add(i);
		Collections.sort(l);
		for (int i = 0; i < a.length; i++)
			a[i] = l.get(i);
	}

	static void sort(int[] a) {
		ArrayList<Integer> l = new ArrayList<>();
		for (int i : a)
			l.add(i);
		Collections.sort(l);
		for (int i = 0; i < a.length; i++)
			a[i] = l.get(i);
	}

	public static int lowerBound(ArrayList<Integer> array, int length, long value) {
		int low = 0;
		int high = length;
		while (low < high) {
			final int mid = (low + high) / 2;
			if (value <= array.get(mid)) {
				high = mid;
			} else {
				low = mid + 1;
			}
		}
		return low;
	}

	public static long mul(long a, long b) {
		return (a * b) % MOD;
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

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

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

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

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

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

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

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

	static long gcd(long a, long b) {
		if (a == 0)
			return b;
		return gcd(b % a, a);
	}

	static long lcm(long a, long b) {
		return (a * b) / gcd(a, b);
	}

	public static void sortbyColumn(int[][] att, int col) {
		// Using built-in sort function Arrays.sort
		Arrays.sort(att, new Comparator<int[]>() {

			@Override
			// Compare values according to columns
			public int compare(final int[] entry1, final int[] entry2) {

				// To sort in descending order revert
				// the '>' Operator
				// if (entry1[col] > entry2[col])
				// return 1;
				// else //(entry1[col] >= entry2[col])
				// return -1;
				return new Integer(entry1[col]).compareTo(entry2[col]);
				// return entry1[col].
			}
		}); // End of function call sort().
	}

	public static void sortbyColumn(double[][] att, int col) {
		// Using built-in sort function Arrays.sort
		Arrays.sort(att, new Comparator<double[]>() {

			@Override
			// Compare values according to columns
			public int compare(final double[] entry1, final double[] entry2) {

				// To sort in descending order revert
				// the '>' Operator
				// if (entry1[col] > entry2[col])
				// return 1;
				// else //(entry1[col] >= entry2[col])
				// return -1;
				return new Double(entry1[col]).compareTo(entry2[col]);
				// return entry1[col].
			}
		}); // End of function call sort().
	}

	static class pair {
		int V, I;

		pair(int v, int i) {
			V = v;
			I = i;
		}
	}

	public static int[] swap(int data[], int left, int right) {
		int temp = data[left];
		data[left] = data[right];
		data[right] = temp;
		return data;
	}

	public static int[] reverse(int data[], int left, int right) {
		while (left < right) {
			int temp = data[left];
			data[left++] = data[right];
			data[right--] = temp;
		}
		return data;
	}

	public static boolean findNextPermutation(int data[]) {
		if (data.length <= 1)
			return false;

		int last = data.length - 2;
		while (last >= 0) {
			if (data[last] < data[last + 1]) {
				break;
			}
			last--;
		}
		if (last < 0)
			return false;

		int nextGreater = data.length - 1;
		for (int i = data.length - 1; i > last; i--) {
			if (data[i] > data[last]) {
				nextGreater = i;
				break;
			}
		}
		data = swap(data, nextGreater, last);
		data = reverse(data, last + 1, data.length - 1);
		return true;
	}

	static long ncr(long a, long b) {
		if (b > a - b)
			return ncr(a, a - b);
		long ansMul = 1;
		long ansDiv = 1;
		for (int i = 0; i < b; i++) {
			ansMul *= (a - i);
			ansDiv *= (i + 1);
			ansMul %= MOD;
			ansDiv %= MOD;
		}

		long ans = ansMul * power(ansDiv, MOD - 2, MOD) % MOD;

		return ans;
	}

	static long __gcd(long n1, long n2) {
		long gcd = 1;

		for (int i = 1; i <= n1 && i <= n2; ++i) {
			// Checks if i is factor of both integers
			if (n1 % i == 0 && n2 % i == 0) {
				gcd = i;
			}
		}
		return gcd;
	}

	static long power(long prev, long n2, long mod2) {
		long res = 1;

		prev = prev % mod2;

		if (prev == 0)
			return 0;
		while (n2 > 0) {

			if ((n2 & 1) == 1)
				res = (res * prev) % mod2;

			n2 = n2 >> 1;
			prev = (prev * prev) % mod2;
		}
		return res;
	}

	static long modInverse(long fac2, int p) {
		return power(fac2, p - 2, p);
	}

	static boolean isPrime(int n) {
		// Corner cases
		if (n <= 1)
			return false;
		if (n <= 3)
			return true;

		// This is checked so that we can skip
		// middle five numbers in below loop
		if (n % 2 == 0 || n % 3 == 0)
			return false;

		for (int i = 5; i * i <= n; i = i + 6)
			if (n % i == 0 || n % (i + 2) == 0)
				return false;

		return true;
	}

	public static BigInteger lcmm(String a, String b) {
		BigInteger s = new BigInteger(a);
		BigInteger s1 = new BigInteger(b);
		BigInteger mul = s.multiply(s1);
		BigInteger gcd = s.gcd(s1);
		BigInteger lcm = mul.divide(gcd);
		return lcm;
	}
	/*
	 * static boolean prime[] = new boolean[10000007]; static int spf[] = new
	 * int[10000007];
	 *
	 * public static void sieveOfEratosthenes(int n) { for (int i = 2; i < n;
	 * i++) prime[i] = true; for (int p = 2; p * p <= n; p++) {
	 *
	 * if (prime[p] == true) {
	 *
	 * for (int i = p * p; i <= n; i += p) { prime[i] = false; spf[i] = p; } } }
	 * }
	 */
}

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


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

public class Main {
    public static void main(String[] args) throws Exception {
        FastScanner sc = new FastScanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = sc.nextInt();
        int k = sc.nextInt();
        long[] a = sc.nextLongArray(n);
        if(k == 0){
            long max = 0;
            for(long v : a){
                max = Math.max(max,v);
            }
            pw.println(max);
        }else{
            int left = 0;
            int right = (int)1e9+1;
            while(right - left > 1){
                int mid = (right+left)/2; //丸太の最大長さ
                int cnt = 0;              //何回切るか
                for(int i = 0; i < n; i++){
                    if(mid >= a[i]){
                        continue;
                    }
                    cnt += (int)(a[i]/mid);
                    if(a[i]%mid == 0){
                        cnt--;
                    }
                }
                if(cnt <= k){
                    right = mid;
                }else{
                    left = mid;
                }
            }
            pw.println(right);
        }
        pw.flush();
    }

    static class GeekInteger {
        public static void save_sort(int[] array) {
            shuffle(array);
            Arrays.sort(array);
        }

        public static int[] shuffle(int[] array) {
            int n = array.length;
            Random random = new Random();
            for (int i = 0, j; i < n; i++) {
                j = i + random.nextInt(n - i);
                int randomElement = array[j];
                array[j] = array[i];
                array[i] = randomElement;
            }
            return array;
        }

    }
}

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

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

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

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

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

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

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

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

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

Score : 500 points

Problem Statement

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

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

0 \leq K \leq 10^9

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Sample Input 1

2 3
7 9

Sample Output 1

4

First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.

Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.

Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.

In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.

Sample Input 2

3 0
3 4 5

Sample Output 2

5

Sample Input 3

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Sample Output 3

292638192


import java.util.Scanner;
public class Main {
public static void main(String args[]) {
	Scanner sc =new Scanner(System.in);
	int r=sc.nextInt();
	int g=sc.nextInt();
	int b=sc.nextInt();
	int k=sc.nextInt();
	while(k>0) {
		if(b<g&&b<r) {
			b=b*2;

		}else if(g<r) {
			g=g*2;

		}else if(r<g&&g<b) {
			b=b*2;

		}else if(b<g||b<r) {
			b=b*2;

		}else if(r==b&&b==g) {
			b=b*2;

		}else if(r==g) {
			g=g*2;

		}else if(r==b) {
			b=b*2;
		}else if(g==b) {
			b=b*2;
		}

		k--;
	}
	int flag=0;
	if(b>g&&g>r) {
		System.out.println("Yes");
	}else {
		System.out.println("No");
	}

}
}

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


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

public class Main{
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}
        String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOException  e){e.printStackTrace();}}return st.nextToken();}
        int nextInt(){return Integer.parseInt(next());}
        long nextLong(){return Long.parseLong(next());}
        double nextDouble(){return Double.parseDouble(next());}
        int[] readArray(int n){int[] a=new int[n];for (int i=0; i<n; i++) a[i]=nextInt();return a;}
        long[] readLongArray(int n){long[] a=new long[n];for (int i=0; i<n; i++) a[i]=nextLong();return a;}
        String nextLine(){String str = "";try{str = br.readLine();}catch (IOException e){e.printStackTrace();}return str;}
    }
    static int getgcd(int n1,int n2){
        while(n1 != n2){
            if(n1 > n2) n1 -= n2;
            else n2 -= n1;
        }
        return n1;
    }
    static boolean isSorted(int[] arr, int n){
        for(int i=1;i<n;i++){
            if(arr[i]<arr[i-1]) return false;
        }
        return true;
    }
    static boolean isPrime(long n){
        if(n==2) return true;
        else if(n%2==0) return false;
        for(int i=3;i<=n/2;i+=2){
            if(n%i==0) return false;
        }
        return true;
    }
    static void printArray(int[] arr){
        for(int x:arr){
            System.out.print(x+" ");
        }
        System.out.println();
    }
    public static void main(String[] args) throws NumberFormatException, IOException {
        FastReader s=new FastReader();
        int a=s.nextInt(),b=s.nextInt(),c=s.nextInt(),k=s.nextInt();
        int count=0;
        while((b)<=a){
            b*=2;count++;
        }
        while((c)<=a){
            c*=2;count++;
        }
        if(count<=k) System.out.println("Yes");
        else System.out.println("No");
    }
}


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();int k=sc.nextInt();int[] array = new int[n];
        for(int i=0;i<n;i++){
            array[i] = sc.nextInt();
        }
        int plus=0;int count=0;
        while (count<n-k){
            int first_group = 0; int second_group =0;
            for(int i=0;i<k;i++){
                first_group+=array[i+plus];
                second_group+=array[i+plus+1];
            }
            plus++;
            if(second_group-first_group>0) {
                System.out.println("Yes");
                count++;
            }
            else{
                System.out.println("No");
                count++;
            }

        }
    }
}

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < a.length; i++) {
			a[i] = sc.nextInt();
		}

		for (int i = k; i < n; i++) {
			System.out.println(a[i - k] < a[i] ? "Yes" : "No");
		}
	}

}


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

public class Main {
	static final long MOD = 1000000007L;
	static final int INF = 50000000;
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		PrintWriter pw = new PrintWriter(System.out);

		int N = sc.ni();
		ArrayList<int[]> up = new ArrayList<int[]>();
		ArrayList<int[]> down = new ArrayList<int[]>();
		ArrayList<int[]> left = new ArrayList<int[]>();
		ArrayList<int[]> right = new ArrayList<int[]>();
		for (int i = 0; i < N; i++) {
			int x = sc.ni();
			int y = sc.ni();
			char c  = sc.next().charAt(0);
			int[] pair = new int[] {x,y,c};
			if (c=='U')
				up.add(pair);
			else if (c=='D')
				down.add(pair);
			else if (c=='L')
				left.add(pair);
			else
				right.add(pair);
		}
		int ans = INF;
		PriorityQueue<int[]> pq1 = new PriorityQueue<int[]>(new Comparator<int[]>() {
			@Override
			public int compare(int[] arr1, int[] arr2) {
				return arr1[0]-arr2[0];
			}
		});
		PriorityQueue<int[]> pq2 = new PriorityQueue<int[]>(new Comparator<int[]>() {
			@Override
			public int compare(int[] arr1, int[] arr2) {
				return arr2[0]-arr1[0];
			}
		});

		//UR
		for (int[] pair: up)
			pq1.add(pair);
		for (int[] pair: right)
			pq1.add(pair);
		HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
		while (!pq1.isEmpty()) {
			int[] pair = pq1.poll();
			int val = pair[1]+pair[0];
			if (pair[2]=='U') {
				if (hm.containsKey(val)) {
					int diff = Math.abs(pair[0]-hm.get(val));
					ans = Math.min(ans,diff);
				}
			} else {
				hm.put(val, pair[0]);
			}
		}
		//UL
		for (int[] pair: up)
			pq2.add(pair);
		for (int[] pair: left)
			pq2.add(pair);
		hm = new HashMap<Integer,Integer>();
		while (!pq2.isEmpty()) {
			int[] pair = pq2.poll();
			int val = pair[1]-pair[0];
			if (pair[2]=='U') {
				if (hm.containsKey(val)) {
					int diff = Math.abs(hm.get(val)-pair[0]);
					ans = Math.min(ans,diff);
				}
			} else {
				hm.put(val, pair[0]);
			}
		}
		//DR
		for (int[] pair: down)
			pq1.add(pair);
		for (int[] pair: right)
			pq1.add(pair);
		hm = new HashMap<Integer,Integer>();
		while (!pq1.isEmpty()) {
			int[] pair = pq1.poll();
			int val = pair[1]-pair[0];
			if (pair[2]=='D') {
				if (hm.containsKey(val)) {
					int diff = Math.abs(pair[0]-hm.get(val));
					ans = Math.min(ans,diff);
				}
			} else {
				hm.put(val, pair[0]);
			}
		}

		//DL
		for (int[] pair: down)
			pq2.add(pair);
		for (int[] pair: left)
			pq2.add(pair);
		hm = new HashMap<Integer,Integer>();
		while (!pq2.isEmpty()) {
			int[] pair = pq2.poll();
			int val = pair[1]+pair[0];
			if (pair[2]=='D') {
				if (hm.containsKey(val)) {
					int diff = Math.abs(hm.get(val)-pair[0]);
					ans = Math.min(ans,diff);
				}
			} else {
				hm.put(val, pair[0]);
			}
		}

		int ans2 = INF;
		//UD
		TreeSet<Integer>[] ts = new TreeSet[200001];
		for (int[] pair: down) {
			if (ts[pair[0]]==null) {
				ts[pair[0]] = new TreeSet<Integer>();
			}
			ts[pair[0]].add(pair[1]);
		}
		for (int[] pair: up) {
			if (ts[pair[0]]!=null) {
				Integer collision = ts[pair[0]].higher(pair[1]);
				if (collision != null) {
					int diff = Math.abs(collision-pair[1]);
					ans2 = Math.min(ans2, diff);
				}
			}
		}
		//LR
		for (int i = 0; i <= 200000; i++)
			ts[i] = null;
		for (int[] pair: right) {
			if (ts[pair[1]]==null) {
				ts[pair[1]] = new TreeSet<Integer>();
			}
			ts[pair[1]].add(pair[0]);
		}
		for (int[] pair: left) {
			if (ts[pair[1]]!=null) {
				Integer collision = ts[pair[1]].lower(pair[0]);
				if (collision != null) {
					int diff = Math.abs(pair[0]-collision);
					ans2 = Math.min(ans2, diff);
				}
			}
		}

		int finalAns = Math.min(10*ans, 5*ans2);
		if (finalAns >= INF) {
			pw.println("SAFE");
		} else {
			pw.println(finalAns);
		}

		pw.close();
	}

    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

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

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

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

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

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100


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

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = Integer.parseInt(sc.next());
        PrintWriter pw = new PrintWriter(System.out);
        for(int i=1;i<=N;i++){
            int count = 0;
            for(int x=1;x*x<=N;x++){
                for(int y=1;y*y<=N;y++){
                    for(int z=1;z*z<=N;z++){
                        if(x*x+y*y+z*z+x*y+y*z+z*x==i){
                            count++;
                        }
                    }
                }
            }
            pw.println(count);
            pw.flush();
        }
    }
}

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc =new Scanner(System.in);
    int N =sc.nextInt();
    for(int i=1;i<=N;i++){
      if(i<4){System.out.println(0);}
      else{
      double I =(double)i;
      double T=Math.sqrt(2*I-8);
      double D=Math.sqrt(2*I/3);
      int t =(int)T;
        int d =(int)D;
       long ans =0;
        for(int j=2;j<=d;j++){
        for(int k=j;k<=t;k++){
          int m =Math.max(d,k);
          for(int l=m;l<=t;l++){
            if(j+1<=k+l){
              if(k+1<=j+l){
                if(l+1<=j+k){
            if(j*j+k*k+l*l==2*i){
              ans =ans+3;
              if((j==k)&&(k==l)){ans =ans-2;}
              }}}}}}}
        System.out.println(ans);
      }
    }
  }
}


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

public class Main{
	static FastScanner sc = new FastScanner();
	static PrintWriter out = new PrintWriter(System.out);
	static int n;
	//static HashMap <String, Integer> map;

	public static void main(String[] args) {
		n = sc.nextInt();

		int ac = 0;
		int wa = 0;
		int re = 0;
		int tle = 0;

		for (int i=0; i<n; i++) {
			String s = sc.next();

			if (s.equals("AC"))
				ac++;

			else if (s.equals("RE"))
				re++;

			else if (s.equals("TLE"))
				tle++;

			else
				wa++;
		}

		out.println("AC"+" "+"x"+" "+ac);
		out.println("WA"+" "+"x"+" "+wa);
		out.println("TLE"+" "+"x"+" "+tle);
		out.println("RE"+" "+"x"+" "+re);

		out.flush();

	}

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

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

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

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

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

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

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

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

	    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() {
	      return (int) nextLong();
	    }

	    public int[] nextIntArray(int N, boolean oneBased) {
	      if (oneBased) {
	        int[] array = new int[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      } else {
	        int[] array = new int[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      }
	    }

	    public long[] nextLongArray(int N, boolean oneBased) {
	      if (oneBased) {
	        long[] array = new long[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      } else {
	        long[] array = new long[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      }
	    }

	    public double [] nextDoubleArray(int N, boolean oneBased) {
		      if (oneBased) {
		        double [] array = new double[N + 1];
		        for (int i = 1; i <= N; i++) {
		          array[i] = sc.nextDouble();
		        }
		        return array;
		      } else {
		        double[] array = new double[N];
		        for (int i = 0; i < N; i++) {
		          array[i] = sc.nextDouble();
		        }
		        return array;
		      }
		    }

	  }

}

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


import java.util.Scanner;
public class Main{
  public static void main(String[] args){
	  Scanner scan = new Scanner(System.in);
	  int ac = 0;
	  int wa = 0;
	  int tle = 0;
	  int re = 0;
	  int num = scan.nextInt();
	   String test = "";
	  for(int i=0;i<num+1;i++) {
		  test = scan.nextLine();
		  if (test.equals("AC")) {
			  ac++;
		  }
		  if (test.equals("WA")) {
			  wa++;
		  }
		  if (test.equals("TLE")) {
			  tle++;
		  }
		  if (test.equals("RE")) {
			  re++;
		  }
	  }

	  System.out.println(
			  "AC x " + ac+
			  "\nWA x " + wa+
			  "\nTLE x "+ tle+
			  "\nRE x " + re);
  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.*;
public class Main{
	static long mod=1000000007;
	static int ans=0;
	static char[][] arr;
	static int n;
	static int m;
	static int rem;
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String[] cmd=br.readLine().split(" ");
		n=Integer.valueOf(cmd[0]);
		m=Integer.valueOf(cmd[1]);
		int k=Integer.valueOf(cmd[2]);
		arr=new char[n][m];
		for(int i=0;i<n;i++)
		{
			String s=br.readLine();
			for(int j=0;j<m;j++)
			{
				arr[i][j]=s.charAt(j);
			}
		}
		int cnt=0;
		int[] row=new int[n];
		int[] col=new int[m];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(arr[i][j]=='#')
				{
					cnt++;
					row[i]++;
					col[j]++;
				}
			}
		}
		rem=cnt-k;
		ans=0;
		if(rem==0)
			ans=1;
		else
		{
			for(int i=1;i<=Math.pow(2,n);i++)
			{
				int x=0;
				for(int j=0;j<n;j++)
				{
					if((i&(1<<j))!=0)
						x=x+row[j];
				}
				if(x==rem)
					ans++;
			}
			for(int i=1;i<=Math.pow(2,m);i++)
			{
				int x=0;
				for(int j=0;j<m;j++)
				{
					if((i&(1<<j))!=0)
						x=x+col[j];
				}
				if(x==rem)
					ans++;
			}
//			System.out.println(ans);
			for(int i=1;i<=Math.pow(2, n)-1;i++)
			{
				int x=0;
				int y=0;
				for(int j=0;j<n;j++)
				{
					if((i&(1<<j))!=0)
						y=y+row[j];
				}
				for(int j=1;j<=Math.pow(2, m)-1;j++)
				{
					x=y;
					for(int l=0;l<m;l++)
					{
						if((j&(1<<l))!=0)
							x=x+col[l];
					}
					for(int l=0;l<n;l++)
					{
						if((i&(1<<l))!=0)
						{
						for(int a=0;a<m;a++)
						{
							if((j&(1<<a))!=0)
							{
								if(arr[l][a]=='#')
									x--;
							}
						}}
					}
					if(x==rem)
					{
//						System.out.println(i+" "+j);
						ans++;
					}
				}
			}
		}
		System.out.println(ans);
	}
}

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

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

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long n = sc.nextLong();
		long[] as = new long[(int)n];
		for(long i=0; i<n; i++){
			as[(int)i] = sc.nextLong();
		}
		Arrays.sort(as);
		long ans = 0;
		for(int i=1; i<n; i++){
			ans += as[i];
		}
		System.out.println(ans);

	}
}

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(final String[] args) {
        final FastScanner scanner = new FastScanner(System.in);
        final int n = scanner.nextInt();
        final List<Long> list = IntStream.range(0, n)
            .mapToObj(i -> scanner.nextLong())
            .sorted(Comparator.reverseOrder())
            .collect(Collectors.toList());

        final Deque<Long> queue = new ArrayDeque<>();
        queue.add(list.get(0));
        queue.add(list.get(1));
        long sum = list.get(0);
        final Deque<Long> tmp = new ArrayDeque<>();
        for (int i = 2; i < n; i++) {
            if (queue.isEmpty()) {
                queue.addAll(tmp);
                tmp.clear();
            }

            final long a = queue.pollFirst();
            final long b = queue.isEmpty() ? list.get(0) : queue.peekFirst();
            sum += Math.min(a, b);
            final long value = list.get(i);
            tmp.add(a);
            tmp.add(value);
        }

        System.out.println(sum);
    }

    private static class FastScanner {
        private final BufferedReader reader;
        private StringTokenizer tokenizer;

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

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

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

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

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

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

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


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

public class Main {
    public static void main(String[] args) throws Exception {
        FastScanner sc = new FastScanner(System.in);
        int n = sc.nextInt();
        ArrayList<Integer> a = new ArrayList<>();
        for(int i = 0; i < n; i++){
            a.add(sc.nextInt());
        }
        Collections.sort(a,Comparator.reverseOrder());
        long ans = a.get(0);
        int cnt = 1;
        int index = 1;
        while(cnt < n-1){
            if(n-1-cnt == 1){
                ans += a.get(index);
                cnt++;
            }else{
                ans += a.get(index)*2;
                cnt += 2;
            }
            index++;
        }
        System.out.println(ans);
    }

}

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

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

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

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

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

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

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

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

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


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		try (Scanner scn = new Scanner(System.in)) {
			int num = scn.nextInt();
			System.out.println(num + (num*num) + (num*num*num));
		}
	}
}

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


import java.util.*;

class Main{
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    String str_S = sc.next();
    char[] s = str_S.toCharArray();
    String str_T = sc.next();
    char[] t = str_T.toCharArray();
    int result = 0;
    for(int i = 0;i < s.length;i++) {
      if(s[i] != t[i]) {
        result++;
      }
    }
    System.out.println(result);
  }
}

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


import java.util.*;
import java.io.*;
public class Main{
   public static void main(String[] main) throws Exception{
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = new StringTokenizer(br.readLine());
      PrintWriter out = new PrintWriter(System.out);
      int n = Integer.parseInt(st.nextToken());
      st = new StringTokenizer(br.readLine());
      long a1 = 0, a2 = 0;
      long xor = 0;
      for(int i = 0; i < n; i++) {
    	  long a = Long.parseLong(st.nextToken());
    	  if(i == 0)
    		  a1 = a;
    	  else if(i == 1)
    		  a2 = a;
    	  else
    		  xor = a ^ xor;
      }
      long sum = a1 + a2;
      long res = 0;
      PriorityQueue<Long> one = new PriorityQueue<Long>();
      boolean works = true;
      long pow = 1;
      while(sum > 0) {
    	  if(sum%2 == xor%2) {
    		  if(sum%2 == 1)
    			  one.add(-pow);
    		  else {
    			  if(sum%4 != xor%4) {
	    			  res += pow;
	    			  sum -= 2;
    			  }
    		  }
    	  }
    	  else {
    		  works = false;
    		  break;
    	  }
    	  sum /= 2;
    	  xor /= 2;
    	  pow *= 2;
      }
      if(!works || res > a1 || xor > 0)
    	  out.println(-1);
      else {
    	  while(one.size() > 0) {
    		  pow = -one.remove();
    		  if(res + pow <= a1)
    			  res += pow;
    	  }
    	  if(res == 0)
    		  out.println(-1);
    	  else
    		  out.println(a1 - res);
      }
      out.close();
   }
}

Score : 600 points

Problem Statement

There are N piles of stones. The i-th pile has A_i stones.

Aoki and Takahashi are about to use them to play the following game:

Starting with Aoki, the two players alternately do the following operation:

Operation: Choose one pile of stones, and remove one or more stones from it.

When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

Constraints

2 \leq N \leq 300

1 \leq A_i \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead.

Sample Input 1

2
5 3

Sample Output 1

1

Without moving stones, if Aoki first removes 2 stones from the 1-st pile, Takahashi cannot win in any way.

If Takahashi moves 1 stone from the 1-st pile to the 2-nd before the game begins so that both piles have 4 stones, Takahashi can always win by properly choosing his actions.

Sample Input 2

2
3 5

Sample Output 2

-1

It is not allowed to move stones from the 2-nd pile to the 1-st.

Sample Input 3

3
1 1 2

Sample Output 3

-1

It is not allowed to move all stones from the 1-st pile.

Sample Input 4

8
10 9 8 7 6 5 4 3

Sample Output 4

3

Sample Input 5

3
4294967297 8589934593 12884901890

Sample Output 5

1

Watch out for overflows.