import java.util.Scanner;

public class Main
{

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt()+1;
		int m = sc.nextInt(); //largest step

		OAVL con = new OAVL();

		String s = sc.next();

		boolean[] hole = new boolean[n];
		for(int i = 0; i < n; i++)
		{
			if(s.charAt(i) == '1')hole[i] = true;
		}

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

		int[] minid = new int[n]; //smallest id for each step-to-fin

		for(int i = n-2; i >= 0; i--)
		{
			//remove i+m+1 from consideration
			if(i+m+1 < n-1 && !hole[i+m+1])
			{
				con.remove(dp[i+m+1]);
			}
			if(hole[i])continue;

			//n-1 is already finish!
			//1 step from fin?
			if(i+m >= n-1)
			{
				dp[i] = 1;
				step[i] = n-1;
			}
			else
			{
				//step into one of the considered places
				if(con.getSmallest(con.root) == null || con.getSmallest(con.root).value >= 999999999)
				{ //no way from here!!
					dp[i] = 999999999;
					step[i] = n-1;
				}
				else
				{
					int cur = (int)con.getSmallest(con.root).value;
					dp[i] = cur+1;
					step[i] = minid[cur];
				}
			}

//			System.out.println(i + ": " + dp[i] + ", step " + step[i]);
			//add to consideration
			con.add(dp[i]);

			if(dp[i] < 999999999)
				minid[dp[i]] = i;
		}
//		System.out.println(dp[0] + " steps");
		int steps = dp[0];

		if(steps >= 999999999)
		{
			System.out.println(-1);
			return;
		}

		int pos = 0;

		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < steps; i++)
		{
			if(i>0)sb.append(' ');
			sb.append((step[pos]-pos));
			pos = step[pos];
		}
		System.out.println(sb);
	}

	static class OAVL
	{ //Occurrence AVL Tree!
		Node root = null;
		int nodes = 0;

		//I think this was O(log n)
		int getNumberOfEqualOrGreater(long val)
		{
			return getNumberOfEqualOrGreater(val, root);
		}

		private int getNumberOfEqualOrGreater(long val, Node pos)
		{
			if(pos==null)return 0;
			if(val == pos.value)
			{
				if(pos.r != null)return pos.r.subsize+1;
				else return 1;
			}
			else if(val < pos.value)
			{
				int fromR = 0;
				if(pos.r != null)fromR = pos.r.subsize;
				return getNumberOfEqualOrGreater(val, pos.l) + fromR + 1;
			}
			else if(val > pos.value)
			{
				return getNumberOfEqualOrGreater(val, pos.r);
			}

			return 0;
		}

		//I think this was O(log n)
		int getNumberOfEqualOrLesser(long val)
		{
			return getNumberOfEqualOrLesser(val, root);
		}

		private int getNumberOfEqualOrLesser(long val, Node pos)
		{
			if(pos==null)return 0;
			if(val == pos.value)
			{
				if(pos.l != null)return pos.l.subsize+1;
				else return 1;
			}
			else if(val > pos.value)
			{
				int fromL = 0;
				if(pos.l != null)fromL = pos.l.subsize;
				return getNumberOfEqualOrLesser(val, pos.r) + fromL + 1;
			}
			else if(val < pos.value)
			{
				return getNumberOfEqualOrLesser(val, pos.l);
			}

			return 0;
		}

		void add(long i)
		{
			root = insert(root, i);
		}

		private Node insert(Node pos, long i)
		{
			if(pos == null)
			{ //place here
				nodes++;
				return new Node(i);
			}
			if(pos.value == i)
			{
				pos.number++;
				return pos; //already here!
			}

			if(i < pos.value)
			{ //go left
				pos.l = insert(pos.l, i);
			}
			else
			{
				pos.r = insert(pos.r, i);
			}

			pos.update();
			return balance(pos);
		}

		long getSmallestThatIsBiggerThan(long val)
		{
			return getSmallestThatIsBiggerThan(root, val);
		}

		private long getSmallestThatIsBiggerThan(Node pos, long val)
		{
//			if(pos == null)System.out.println("Pos null");
//			System.out.println("Searching at " + pos.value);
			if(pos.value <= val)
			{ //need bigger
				if(pos.r != null)
					return getSmallestThatIsBiggerThan(pos.r, val);
				else
				{
					return 999999999;
				}
			}
			else
			{ //this or smaller
				if(pos.l != null)
				{
					return Math.min(pos.value, getSmallestThatIsBiggerThan(pos.l, val));
				}
				else return pos.value;
			}
		}

		long getBiggestThatIsSmallerThan(long val)
		{
			return getBiggestThatIsSmallerThan(root, val);
		}

		private long getBiggestThatIsSmallerThan(Node pos, long val)
		{
			if(pos.value >= val)
			{ //need smaller
				if(pos.l != null)
					return getBiggestThatIsSmallerThan(pos.l, val);
				else
				{
					return -999999999;
				}
			}
			else
			{ //this or bigger
				if(pos.r != null)
				{
					return Math.max(pos.value, getBiggestThatIsSmallerThan(pos.r, val));
				}
				else return pos.value;
			}
		}
		Node getSmallest(Node pos)
		{
			if(pos == null)return pos;
			if(pos.l == null)
				return pos;
			else return getSmallest(pos.l);
		}

		Node getLargest(Node pos)
		{
			if(pos.r == null)
				return pos;
			else return getLargest(pos.r);
		}

		void remove(long i)
		{
			root = delete(root, i);
		}

		private Node delete(Node pos, long i)
		{
			if(pos == null)
			{ //already non-existent
				return null;
			}
			if(pos.value == i)
			{
				//delete this
				if(pos.number > 1) //when there's only 1 left, delete.
				{
					pos.number--;
					return pos;
				}
				//MARK

				if(pos.l != null && pos.r != null)
				{
					//you can do either but let's remove from the subtree with bigger height.
					if(pos.l.height >= pos.r.height)
					{
						Node dum = getLargest(pos.l); //return largest of left subtree
						pos.value = dum.value; //copy its value
						pos.l = delete(pos.l, dum.value); //then remove that, while updating all nodes necessary
					}
					else
					{
						Node dum = getSmallest(pos.r); //return smallest of right subtree
						pos.value = dum.value; //copy its value
						pos.r = delete(pos.r, dum.value); //then remove that, while updating all nodes necessary
					}
				}
				else if(pos.l != null)
				{
					pos = pos.l;
				}
				else if(pos.r != null)pos = pos.r;
				else //both are null
				{
					return null;
				}
			}

			else if(i < pos.value)
			{ //go left
				pos.l = delete(pos.l, i);
			}
			else
			{
				pos.r = delete(pos.r, i);
			}

			pos.update();
			return balance(pos);
		}

		Node leftRotate(Node node)
		{
			Node b = node.r;
			node.subsize -= b.subsize;
			node.r = b.l;
			if(b.l!=null)node.subsize += b.l.subsize;

			if(b.l!=null)b.subsize -= b.l.subsize;
			b.l = node;
			b.subsize += node.subsize;

			node.update();
			b.update();
			return b;
		}

		Node rightRotate(Node node)
		{
			Node b = node.l;
			node.subsize -= b.subsize;
			node.l = b.r;
			if(b.r!=null)node.subsize += b.r.subsize;

			if(b.r!=null)b.subsize -= b.r.subsize;
			b.r = node;
			b.subsize += node.subsize;

			node.update();
			b.update();
			return b;
		}

		Node llCase(Node node)
		{
			return rightRotate(node);
		}

		Node lrCase(Node node)
		{
			node.l = leftRotate(node.l);
			return rightRotate(node);
		}

		Node rrCase(Node node)
		{
			return leftRotate(node);
		}

		Node rlCase(Node node)
		{
			node.r = rightRotate(node.r);
			return leftRotate(node);
		}

		Node balance(Node node)
		{
			if(node.balance <= -2)
			{
				if(node.l.balance <= 0)
					return llCase(node);
				else
					return lrCase(node);
			}
			else if(node.balance >= 2)
			{
				if(node.r.balance >= 0)
					return rrCase(node);
				else
					return rlCase(node);
			}

			return node; //already balanced!
		}

		void printout(Node pos)
		{
			if(pos == null)return;
			pos.printout();
			if(pos.l != null)System.out.println(pos.value + "'s L");
			printout(pos.l);
			if(pos.r != null)System.out.println(pos.value + "'s R");
			printout(pos.r);
		}

		static class Node
		{
			int balance = 0;
			int height = 0;
			long value;

			int number = 1;

			int subsize = 1; //size of subtree rooted here, i.e. descendants + 1 (self)

			Node l = null;
			Node r = null;

			void printout()
			{
				System.out.println("Value " + value + " height " + height + " subsize " + subsize + " balance " + balance);
			}

			void update()
			{ //leaf has height of 0.
				subsize = 1;
				if(l != null)subsize += l.subsize;
				if(r != null)subsize += r.subsize;

				int lh = -1;
				int rh = -1;
				if(l!=null)lh = l.height;
				if(r!=null)rh = r.height;
				height = 1 + Math.max(lh, rh);

				balance = rh - lh;
			}

			public Node(long i)
			{
				value = i;
			}
		}
	}

}

Score : 600 points

Problem Statement

Takahashi is playing a board game called Sugoroku.

On the board, there are N + 1 squares numbered 0 to N. Takahashi starts at Square 0, and he has to stop exactly at Square N to win the game.

The game uses a roulette with the M numbers from 1 to M. In each turn, Takahashi spins the roulette. If the number x comes up when he is at Square s, he moves to Square s+x. If this makes him go beyond Square N, he loses the game.

Additionally, some of the squares are Game Over Squares. He also loses the game if he stops at one of those squares. You are given a string S of length N + 1, representing which squares are Game Over Squares. For each i (0 \leq i \leq N), Square i is a Game Over Square if S[i] = 1 and not if S[i] = 0.

Find the sequence of numbers coming up in the roulette in which Takahashi can win the game in the fewest number of turns possible. If there are multiple such sequences, find the lexicographically smallest such sequence. If Takahashi cannot win the game, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

|S| = N + 1

S consists of 0 and 1.

S[0] = 0

S[N] = 0

Input

Input is given from Standard Input in the following format:

N M
S

Output

If Takahashi can win the game, print the lexicographically smallest sequence among the shortest sequences of numbers coming up in the roulette in which Takahashi can win the game, with spaces in between.

If Takahashi cannot win the game, print -1.

Sample Input 1

9 3
0001000100

Sample Output 1

1 3 2 3

If the numbers 1, 3, 2, 3 come up in this order, Takahashi can reach Square 9 via Square 1, 4, and 6. He cannot reach Square 9 in three or fewer turns, and this is the lexicographically smallest sequence in which he reaches Square 9 in four turns.

Sample Input 2

5 4
011110

Sample Output 2

-1

Takahashi cannot reach Square 5.

Sample Input 3

6 6
0101010

Sample Output 3

6


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

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

    final long INF = 1_000_000_000;
    int N = scanner.nextInt();
    int M = scanner.nextInt();
    char[] s = scanner.next().toCharArray();

    long[] dp = new long[N + 1];
    Arrays.fill(dp, INF);
    dp[N] = 0;
    for (int i = N - 1; i >= 0; i--)
      if (s[i] == '0')
        for (int j = i + 1; j <= i + M && j <= N; j++) dp[i] = Math.min(dp[i], dp[j] + 1);
    if (dp[0] == INF) {
      System.out.println(-1);
    } else {
      StringBuilder sb = new StringBuilder();
      int next = 0;
      while (next < N) {
        for (int i = next + 1; i <= next + M && i <= N; i++) {
          if (dp[i] == dp[next] - 1) {
            sb.append(i - next).append(' ');
            next = i;
            break;
          }
        }
      }
      sb.setLength(sb.length() - 1);
      System.out.println(sb.toString());
    }
  }
}

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.util.Scanner;
class Main
{
	public static void main(String args[])
	{
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
		int y=sc.nextInt();

		int sum=0;

		if(x==1){
		sum+=300000;
		}
		else if(x==2){
		sum+=200000;
		}
		else if(x==3){
		sum+=100000;
		}
		else{
		sum+=0;
		}

		if(y==1){
		sum+=300000;
		}
		else if(y==2){
		sum+=200000;
		}
		else if(y==3){
		sum+=100000;
		}
		else{
		sum+=0;
		}

		if(x==1 && y==1){
		sum+=400000;
		}

		System.out.println(sum);
	}
}

Score: 100 points

Problem Statement

We held two competitions: Coding Contest and Robot Maneuver.

In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen.

DISCO-Kun took the X-th place in Coding Contest and the Y-th place in Robot Maneuver.
Find the total amount of money he earned.

Constraints

1 \leq X \leq 205

1 \leq Y \leq 205

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the amount of money DISCO-Kun earned, as an integer.

Sample Input 1

1 1

Sample Output 1

1000000

In this case, he earned 300000 yen in Coding Contest and another 300000 yen in Robot Maneuver. Furthermore, as he won both competitions, he got an additional 400000 yen.
In total, he made 300000 + 300000 + 400000 = 1000000 yen.

Sample Input 2

3 101

Sample Output 2

100000

In this case, he earned 100000 yen in Coding Contest.

Sample Input 3

4 4

Sample Output 3

0

In this case, unfortunately, he was the highest-ranked contestant without prize money in both competitions.


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

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

		long ans = 0;
		long val = 0;
		for (int i = 0; i < m; i++) {
			ans += c[i];
			val += d[i] * c[i];
			ans += val / 9;
			val %= 9;
		}
		ans--;
		if (val == 0) {
			ans--;
		}
		System.out.println(ans);
	}
}

Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.


import java.util.*;

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

        int origin = 1 * 3;

        int thisTime = r * r * 3;

        int result = thisTime / origin;

        System.out.println(result);

    }
}

Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


import java.util.*;

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

		System.out.println((nam*nam)/1);
	}
}


import java.util.*;

public class Main{
  public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);
    int N = sc.nextInt(), T=N/2;
    String S = sc.next();
    if(N % 2 !=0) {
      System.out.println("No");
    } else if(S.substring(0,T).equals(S.substring(T,N))){
      System.out.println("Yes");
    } else {
      System.out.println("No");
    }
  }
}

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


import java.util.Scanner;

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

    int n = sc.nextInt();
    String s = sc.next();

    String a = s.substring(0, n / 2);
    String b = s.substring(n / 2, n);

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


import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int nam = sc.nextInt();
		int har = nam/2;
		String stc = sc.next();

		    String ans = "No";
	    	String front = stc.substring(0, har);
	    	String back  = stc.substring(har, nam);
	    	if (front.equals(back)){
		         ans = "Yes";
	    	}
		System.out.println(ans);
	}
}


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

		int N = sc.nextInt();
		double[] x = new double[N];
		double[] y = new double[N];
		double[] ans = new double[40320];
		double[] aa = new double[]{1,2,4,8,16,32,64,128,256};
		double[] bb = new double[]{0,1,2,6,24,120,720,5040,40320};
		for( int i=0; i<N; i++ ){
			x[i] = sc.nextDouble();
			y[i] = sc.nextDouble();
		}
		int count = 0;
		for( int i=0; i<=N-2; i++ ){
			for( int k=i+1; k<=N-1; k++ ){
				ans[count] = Math.sqrt( (x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]) );
				count++;
			}
		}
		double total = 0;
		for( int i=0; i<40320; i++ ){
			total += ans[i];
		}
		System.out.println(total*aa[N-1]/bb[N]);
	}
}

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


import java.util.*;

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        long[] array = new long[n];

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

        if (n < 2 || array[2] == 0) {
            System.out.println(0);
            return;
        }

        long ans = 1;

        for (int i = 2; i < n; i++) {
            if (array[i - 1] == 0 && array[i] > 0) {
                System.out.println(0);
                return;
            }
            long v = pow(array[i - 1], array[i], 998244353);
            ans *= v;
            ans %= 998244353;
        }

        System.out.println(ans);
    }

    //return a^b mod M O(logB)
    private static long pow(long a, long b, int M) {
        long ret = 1;
        long tmp = a;
        while (b > 0) {
            if ((b & 1) == 1) ret = (ret * tmp) % M;
            tmp = (tmp * tmp) % M;
            b = b >> 1;
        }
        return ret;
    }
}

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


import java.util.*;
//import java.math.BigDecimal;

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

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int[] m = new int[n];
        long answer = 1;
        //BigDecimal answer = BigDecimal.valueOf(1);

        if(sc.nextInt() != 0) answer = 0;
        //if(sc.nextInt() != 0) answer = BigDecimal.valueOf(0);
        else m[0]++;
        for(int i = 1; i < n; i++){
            int x;
            if((x = sc.nextInt()) == 0){
                answer = 0;
                //answer = BigDecimal.valueOf(0);
                break;
            }
            m[x]++;
        }

        for(int i = 1; i < n; i++){
            //answer *= ((long)Math.pow(m[i-1], m[i]) % 998244353);
            //answer = answer.multiply(BigDecimal.valueOf(Math.pow(m[i-1], m[i])));
            for(int j = 0; j < m[i]; j++){
                answer *= m[i-1] % 998244353;
            }
        }

        //System.out.println(answer % 998244353);
        //System.out.println(answer.remainder(BigDecimal.valueOf(998244353)).toBigInteger());
        System.out.println(answer);

    }

}


import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

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

		Map<Long, Long> map = new TreeMap<>();

		for (int i = 0; i < n; i++) {
			Long input = sc.nextLong();
			Long c = map.getOrDefault(input, 0L);
			c++;
			map.put(input, c);
		}
		sc.close();
		if (!map.containsKey(0L)) {
			System.out.println(0);
			return;
		}
		Long before = -1L;
		for (Long key : map.keySet()) {
			if (key != before + 1L) {
				System.out.println(0L);
				return;
			}
			before = key;
		}
		Long size = (long) map.values().size();
		long ans = 1L;
		for (Long i = 0L; i < size - 1L; i++) {
			Long a = map.get(i);
			Long b = map.get(i + 1l);
			ans = ans * (long) Math.pow(a, b);
		}
		System.out.println(ans % 998244353L);
	}
}


import java.util.Scanner;

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

		int ans = sc.nextInt();
		if(ans <= 81 &&((ans %2 ==0) || (ans %3 ==0) || (ans %4 ==0)|| (ans %5 ==0)|| (ans %6 ==0)|| (ans %7 ==0)|| (ans %8 ==0)|| (ans %9 ==0))) {
			System.out.println("Yes");
		} else {
			System.out.println("No");
		}
		// Scannerクラスのインスタンスをクローズ
		sc.close();
	}
}

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


import java.util.*;
public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    long a = sc.nextLong();

    long b = Long.MAX_VALUE /2;
    long c = Long.MAX_VALUE /2;
    List<Long> list = factorization(a);
    for (long i : list) {
        if((a/i + i) < (b + c) ){
          b = a/i;
          c = i;
        }
    }
    System.out.println(b + c -2);
  }

  static List<Long> factorization(long x) {
    List<Long> result = new ArrayList<>();

    while (x >= 4 && x % 2 == 0) {
        result.add((long)2);
        x /= 2;
    }
    long d = 3;
    long q = x / d;
    while (q >= d) {
        if (x % d == 0) {
            result.add(d);
            x = q;
        } else {
            d += 2;
        }
        q = x / d;
    }
    result.add(x);
    return result;
  }
}

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


import java.util.Scanner;
import java.lang.Math;
class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long i = 100000000000L;
        for (long j=1; j<=Math.sqrt((double)n); j++) {
        		if(n%j == 0) {
        			long k = n/j;
        			if (i > (j+k-2)) i = j+k-2;
        		}
        }
        System.out.println(i);
    }
}


import java.util.*;

public class Main {

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

    for (long i = 1; i < n; i++) {
      for (long j = 1; j < n; j++) {
        if(i * j == n) {
          s = Math.min(s,i-1+j-1);
          break;
        }
      }
    }

    System.out.println(s);

  }

}


import java.util.*;

class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();
        if (x >= 1 && x <= 100 && y >= 1 && y <= 100) {
            if (x - (y * 2) >= 0) {
                System.out.println(x - (y * 2));
            } else {
                System.out.println(0);
            }
        }
    }
}

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


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

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int A = sc.nextInt();
		int B = sc.nextInt();
		int ans = Math.max(0, A - B*2);
		System.out.println(ans);
	}

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

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

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

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

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

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

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

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

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


import java.util.Scanner;

public class Main {

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

    System.out.println(Math.max(0, A-2*B));

  }

}


import java.util.*;
public class Main {
	public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int sum = 0;
		int arry[]=new int[N+1];
		for(int i=1;i<=N;i++){
			arry[i]=sc.nextInt();
		}
		for(int i=1;i<=N-1;i++){
			for(int k=i+1;k<=N;k++){
				sum=sum+arry[i]*arry[k];
			}
		}
		System.out.println(sum);
    }
}

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int total = 0;
		int N = sc.nextInt();
		int[] tako = new int[N];
		for(int i = 0; i<N; i++) {
			tako[i] = sc.nextInt();
		}
		for(int j = 0; j<tako.length; j++) {
			for(int k = j+1; k<tako.length; k++) {
				total = total + (tako[j] * tako[k]);
			}
		}
		System.out.println(total);
    }
}


import java.util.Scanner;
class Main {
  public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int sum = 0;
    int number[] = new int[N];
    for(int k=0;k<N;k++) {
       number[k] = sc.nextInt();
    }
    for (int i=0;i<N;i++) {
      for (int j=0;j<N;j++) {
        if (i<j) {
         int con = number[i]*number[j];
         sum += con;
        }
      }
    }
    System.out.println(sum);
  }
}


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

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int s[] = new int[n];
		int ans = 0;
		for (int i = 0; i < n; i++) {
			s[i] = sc.nextInt();
		}
		Arrays.sort(s);
		for (int i = 0; i < n - 2; i++) {
			for (int o = i + 1; o < n - 1; o++) {
				// s[i]+s[o]
				for (int p = o + 1; p < n; p++) {
					if ((s[i] + s[o] > s[p])
							&& (Math.abs(s[i] - s[o]) < s[p])) {
						//System.out.println(s[i]+" "+s[o]+" "+s[p]);
						ans++;
					}
					if(Math.abs(s[i] - s[o]) < s[p]){
						break;
					}
				}

			}

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

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

3 \leq N \leq 2 \times 10^3

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


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

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

    for(int i = 0; i < n; i++)
      list[i] = sc.nextInt();
    Arrays.sort(list);

    int count = 0;
    int a,b,c;
    a: for(int ai = 0; ai < n-2; ai++){
      b: for(int bi = ai+1; bi < n-1; bi++){
        c: for(int ci = bi+1; ci < n; ci++){
    		a = list[ai];
     		b = list[bi];
      		c = list[ci];
    		if(a >= (b+c)){
				break a;
            }
          	if(b >= (c+a))
              continue a;
          	if(c >= (a+b))
              continue b;
          	count++;
        }
      }
    }
    System.out.println(count);
  }
}


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

	//Method addition frame end
}

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


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

@SuppressWarnings("unused")
public class Main {
    private FastScanner in = new FastScanner(System.in);
    private PrintWriter out = new PrintWriter(System.out);
    final int MOD = (int)1e9+7;
    long ceil(long a, long b){return (a + b - 1) / b;}

    void solve() throws Exception{
        int N = in.nextInt(), M = in.nextInt(), L = in.nextInt();
        ArrayList<ArrayList<Edge>> G = new ArrayList<>();
        long[][] g = new long[N][N];
        long INF = Long.MAX_VALUE / 2;
        for(int i = 0; i < N; i++){
            //G.add(new ArrayList<>());
            Arrays.fill(g[i], INF);
        }
        for(int i = 0; i < M; i++){
            int from = in.nextInt()-1;
            int to = in.nextInt()-1;
            long cost = in.nextLong();
            /*
            G.get(from).add(new Edge(from, to, cost));
            G.get(to).add(new Edge(to, from, cost));
            */
            g[from][to] = cost;
            g[to][from] = cost;
        }

        long[][] res = warshallFloyd(g, INF);
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        for(int i = 0; i < N; i++){
            list.add(new ArrayList<>());
            for(int j = 0; j < N; j++){
                if(j == i) continue;
                if(res[i][j] <= L) list.get(i).add(j);
            }
        }

        int Q = in.nextInt();
        for(int i = 0; i < Q; i++){
            int s = in.nextInt()-1, t = in.nextInt()-1;
            int[] num = new int[N];
            Arrays.fill(num, Integer.MAX_VALUE / 2);
            ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
            queue.addLast(s);
            num[s] = -1;

            while(!queue.isEmpty()){
                int v = queue.removeFirst();
                for(int next : list.get(v)){
                    if(num[next] > num[v] + 1){
                        num[next] = num[v] + 1;
                        queue.addLast(next);
                    }
                }
            }

            out.println(num[t] == Integer.MAX_VALUE / 2 ? "-1" : num[t]);
        }
    }

    class Edge implements Comparable<Edge>{
        int from;
        int to;
        long cost;
        public Edge(int f, int t, long c){
            from = f;to = t;cost = c;
        }
        @Override
        public int compareTo(Edge o) {
            return Long.compare(this.cost, o.cost);
        }
    }

    long[][] warshallFloyd(long[][] g, long INF){
        int N = g.length;
        long[][] res = new long[N][N];
        for(int i = 0; i < N; i++){
            for(int j = 0; j < N; j++){
                res[i][j] = g[i][j];
            }
        }

        for(int k = 0; k < N; k++){
            for(int i = 0; i < N; i++){
                for(int j = 0; j < N; j++){
                    if(res[i][k] == INF || res[k][j] == INF) continue;
                    res[i][j] = Math.min(res[i][j], res[i][k] + res[k][j]);
                }
            }
        }

        return res;
    }

    //end solve

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

    private void m() throws Exception {
        solve();
        out.flush();
    }

    static class FastScanner {
        Reader input;

        FastScanner() {this(System.in);}
        FastScanner(InputStream stream) {this.input = new BufferedReader(new InputStreamReader(stream));}

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

        long nextLong() {
            try {
                int sign = 1;
                int b = input.read();
                while ((b < '0' || '9' < b) && b != '-' && b != '+') {
                    b = input.read();
                }
                if (b == '-') {
                    sign = -1;
                    b = input.read();
                } else if (b == '+') {
                    b = input.read();
                }
                long ret = b - '0';
                while (true) {
                    b = input.read();
                    if (b < '0' || '9' < b) return ret * sign;
                    ret *= 10;
                    ret += b - '0';
                }
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }

        double nextDouble() {
            try {
                double sign = 1;
                int b = input.read();
                while ((b < '0' || '9' < b) && b != '-' && b != '+') {
                    b = input.read();
                }
                if (b == '-') {
                    sign = -1;
                    b = input.read();
                } else if (b == '+') {
                    b = input.read();
                }
                double ret = b - '0';
                while (true) {
                    b = input.read();
                    if (b < '0' || '9' < b) break;
                    ret *= 10;
                    ret += b - '0';
                }
                if (b != '.') return sign * ret;
                double div = 1;
                b = input.read();
                while ('0' <= b && b <= '9') {
                    ret *= 10;
                    ret += b - '0';
                    div *= 10;
                    b = input.read();
                }
                return sign * ret / div;
            } catch (IOException e) {
                e.printStackTrace();
                return Double.NaN;
            }
        }

        char nextChar() {
            try {
                int b = input.read();
                while (Character.isWhitespace(b)) {
                    b = input.read();
                }
                return (char) b;
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }
        }

        String nextStr() {
            try {
                StringBuilder sb = new StringBuilder();
                int b = input.read();
                while (Character.isWhitespace(b)) {
                    b = input.read();
                }
                while (b != -1 && !Character.isWhitespace(b)) {
                    sb.append((char) b);
                    b = input.read();
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }

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

        public int[] nextIntArrayDec(int n) {
            int[] res = new int[n];
            for (int i = 0; i < n; i++) {
                res[i] = nextInt() - 1;
            }
            return res;
        }

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

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

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

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

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


import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int nums = sc.nextInt();
        int[] list = new int[nums];
        for(int i = 0; i < nums; i++){
            int num =  sc.nextInt();
            list[i]= num;
        }
        Arrays.sort(list);
        System.out.println(nums);
        for (int k= 2; k <= nums ; k++) {
            int[] copied = Arrays.copyOfRange(list, 0, list.length);
            int count = eatCards(k, copied);
            Arrays.sort(list);
            System.out.println(count);
        }
    }

    public static int eatCards(int k, int[] list){
        int counter = 0;
        for (int j = 0; j < list.length; j++) {
            int num = k;
            if(list[j]!=-1){
                int first = list[j];
                list[j] = -1;
                num--;
                for(int i= j + 1; i < list.length; i++) {
                    if (first != list[i] && list[i] != -1) {
                        num--;
                        first = list[i];
                        list[i] = -1;
                        if(num == 0){
                            counter++;
                            break;
                        }
                    }
                }
            }
        }
        return  counter;
    }
}

Score : 600 points

Problem Statement

Takahashi has N cards. The i-th of these cards has an integer A_i written on it.

Takahashi will choose an integer K, and then repeat the following operation some number of times:

Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)

For each K = 1,2, \ldots, N, find the maximum number of times Takahashi can do the operation.

Constraints

1 \le N \le 3 \times 10^5

1 \le A_i \le N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print N integers.
The t-th (1 \le t \le N) of them should be the answer for the case K=t.

Sample Input 1

3
2 1 2

Sample Output 1

3
1
0

For K = 1, we can do the operation as follows:

Choose the first card to eat.

Choose the second card to eat.

Choose the third card to eat.

For K = 2, we can do the operation as follows:

Choose the first and second cards to eat.

For K = 3, we cannot do the operation at all. Note that we cannot choose the first and third cards at the same time.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

5
2
1
1
1

Sample Input 3

4
1 3 3 3

Sample Output 3

4
1
0
0


import java.util.*;

public class Main{
	public static void main (String[] args){
		Scanner sc = new Scanner(System.in);
		int counter=0;
		int N= sc.nextInt();
		int f = 0;
		int count = 0;
		for(int i = 1; i <= N; i++){
			f = i%2;
			if(f == 1){
				counter+=1;
			}
		}
		System.out.println((double)counter/N);
	}
}

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


import java.util.*;
public class Main{
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        double N = sc.nextInt();
        double a = 0;
if(N%2 == 0) a = (double)(1.0/2.0);
else a = ((int)((N/2)+1))/N;

System.out.println(a);
    }
}


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 H[] = new int[N];
		for(int i = 0 ; i < N ; ++i){
			H[i] = sc.nextInt();
		}
		int ret = 0;
		for(int h : H){
			if(h >= K){
				++ret;
			}
		}
		System.out.println(ret);
	}
}

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


import java.util.*;

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

		for(int i = 0;i<n;i++) {
			h[i] = sc.nextInt();
			a[h[i]-1] = i+1;
		}

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

		sc.close();
	}
}

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.function.Supplier;

public class Main {

    static void solve() {
        long a = nextLong();
        long b = nextLong();

        long c = gcd(a, b);
        debug("gcd=" + c);
        List<Long> primes = _primeFactorize(c);
        debug(() -> Arrays.toString(primes.toArray()));
        Set<Long> set = new HashSet<>(primes);
        out.println(set.size() + 1);
    }

    static final int MOD = 1_000_000_007;
    static long[] fac, finv, inv;

    // 階乗(n!)
    static long factorial(long n) {
        long ans = 1;
        for (long i = n; i > 0; i--) {
            ans = ans * i % MOD;
        }
        return ans;
    }

    // nCkの初期化
    static void comInit(int max) {
        fac = new long[max];
        finv = new long[max];
        inv = new long[max];
        fac[0] = fac[1] = 1;
        finv[0] = finv[1] = 1;
        inv[1] = 1;

        for (int i = 2; i < max; i++) {
            fac[i] = fac[i - 1] * i % MOD;
            inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
            finv[i] = finv[i - 1] * inv[i] % MOD;
        }
    }

    // nCkの計算
    static long com(int n, int k) {
        if (n < k)
            return 0;
        if (n < 0 || k < 0)
            return 0;
        return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
    }

    // 素因数分解
    static List<Long> primeFactorize(long n) {
        List<Long> list = new ArrayList<>();
        long tmp = n;
        for (int i = 2; i * i <= n; i++) {
            while (true) {
                if (tmp % i == 0) {
                    list.add((long) i);
                    tmp /= i;
                } else {
                    break;
                }
            }
        }
        if (tmp != 1)
            list.add(tmp);
        return list;
    }

    static Map<Long, List<Long>> primeFactors = new HashMap<>();

    // 素因数分解
    static List<Long> _primeFactorize(long n) {
        if (primeFactors.containsKey(n))
            return primeFactors.get(n);

        List<Long> list = new ArrayList<>();
        if (n % 2 == 0) {
            list.addAll(_primeFactorize(n / 2));
            list.add(2l);
        } else {
            boolean ok = true;
            for (int j = 3; j * j <= n; j += 2) {
                if (n % j == 0) {
                    list.addAll(_primeFactorize(n / j));
                    list.addAll(_primeFactorize(j));
                    ok = false;
                    break;
                }
            }
            if (ok) {
                if (n != 1)
                    list.add(n);
            }
        }

        primeFactors.put(n, Collections.unmodifiableList(list));
        return list;
    }

    // 2〜nまでの数値を素因数分解したmapを返す.
    // map: 数値 -> (素因数)
    // ex)
    // 2 -> (2)
    // 4 -> (2,2)
    // 12 -> (2,2,3)
    @Deprecated // primeFactorizeを使うべき
    static Map<Integer, List<Integer>> primeFactorizeTo(int n) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 2; i <= n; i++) {
            List<Integer> list = new ArrayList<>();
            int tmp = i;
            for (int j = i - 1; j > 1; j--) {
                if (tmp % j == 0) {
                    if (map.containsKey(j)) {
                        list.addAll(map.get(j));
                    } else {
                        list.add(j);
                    }
                    tmp /= j;
                }
            }
            if (tmp != 1)
                list.add(tmp);
            map.put(i, list);
        }
        return map;
    }

    static PrintWriter out;
    static Scanner sc;
    static boolean debugEnabled;
    static long start;
    static long end;

    static int[][] newIntArray(int h, int w, int value) {
        int[][] ret = new int[h][w];
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                ret[i][j] = value;
            }
        }
        return ret;
    }

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

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

    static String nextString() {
        return sc.next();
    }

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

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

    static List<Integer> nextIntList(int n) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(nextInt());
        }
        return list;
    }

    static List<Double> nextDoubleList(int n) {
        List<Double> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add((double) nextInt());
        }
        return list;
    }

    static List<Long> nextLongList(int n) {
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(nextLong());
        }
        return list;
    }

    static char[][] nextCharArray(int h, int w) {
        char[][] c = new char[h][w];
        for (int i = 0; i < h; i++) {
            String str = nextString();
            for (int j = 0; j < w; j++) {
                c[i][j] = str.charAt(j);
            }
        }
        return c;
    }

    // 昇順
    static <T extends Comparable<? super T>> List<T> sort(List<T> list) {
        return sortAsc(list);
    }

    // 昇順
    static <T extends Comparable<? super T>> List<T> sortAsc(List<T> list) {
        Collections.sort(list);
        return list;
    }

    // 降順
    static <T extends Comparable<? super T>> List<T> sortDesc(List<T> list) {
        Collections.sort(list, (e1, e2) -> e2.compareTo(e1));
        return list;
    }

    // greatest common divisor
    // 最大公約数
    static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    // least common multiple
    // 最小公倍数
    static long lcm(long a, long b) {
        if (a > b) {
            return (a / gcd(a, b)) * b;
        } else {
            return (b / gcd(a, b)) * a;
        }
    }

    // least common multiple
    // 最小公倍数
    // 素因数分解されたListを引数とした場合
    static List<Integer> lcm(List<Integer> a, List<Integer> b) {
        List<Integer> ret = new ArrayList<>(a);
        List<Integer> tmp = new ArrayList<>(b);
        for (Integer i : a) {
            if (tmp.contains(i))
                tmp.remove(i);
        }
        ret.addAll(tmp);
        return ret;
    }

    // baseのn乗を計算を返す
    static int pow(int base, int n) {
        int ret = 1;
        for (int i = 0; i < n; i++) {
            ret *= base;
        }
        return ret;
    }

    // return n^k mod m
    static long powMod(long n, long k, long m) {
        if (k == 0) {
            return 1;
        } else if (k % 2 == 1) {
            return powMod(n, k - 1, m) * n % m;
        } else {
            long tmp = powMod(n, k / 2, m);
            return tmp * tmp % m;
        }
    }

    // intをlength桁のbit文字列に変換
    static String toBitString(int length, int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = length - 1; i >= 0; i--) {
            if ((n >> i) % 2 == 1) {
                sb.append("1");
            } else {
                sb.append("0");
            }
        }
        return sb.toString();
    }

    static void setDebugEnabled() {
        String className = new Object() {
        }.getClass().getEnclosingClass().getSimpleName();

        if (!className.equals("Main"))
            debugEnabled = true;
    }

    static void debug(String msg) {
        if (debugEnabled)
            System.err.println(msg);
    }

    static void debug(Supplier<String> msg) {
        if (debugEnabled)
            System.err.println(msg.get());
    }

    static class UnionFind {
        int[] parent;

        UnionFind(int n) {
            parent = new int[n];
            init();
        }

        void init() {
            for (int i = 0; i < parent.length; i++) {
                parent[i] = i;
            }
        }

        int getRoot(int i) {
            if (parent[i] == i) {
                return i;
            } else {
                return parent[i] = getRoot(parent[i]);
            }
        }

        boolean isSame(int x, int y) {
            return getRoot(x) == getRoot(y);
        }

        void unit(int x, int y) {
            x = getRoot(x);
            y = getRoot(y);
            if (x != y) {
                parent[x] = y;
            }

        }
    }

    public static void main(String[] args) {
        preProcess();
        // System.exit(0)で終了した場合も、解答を出力するためにはshutdown hookの設定が必要
        // しかし、これを有効化すると100[msec]程度処理時間が長くなる
        // Runtime.getRuntime().addShutdownHook(new Thread(() -> postProcess()));
        solve();
        postProcess();
    }

    static void preProcess() {
        start = System.nanoTime();
        setDebugEnabled();
        out = new PrintWriter(System.out);
        sc = new Scanner(System.in);
    }

    static void postProcess() {
        out.flush();
        sc.close();
        end = System.nanoTime();
        debug(() -> "elapsed time: " + (end - start) / 1_000_000 + "[msec]");
    }

}

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


import java.util.Scanner;
import java.util.ArrayDeque;
import java.util.Deque;

class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
        long a = sc.nextLong();
        long b = sc.nextLong();
        int count = 0;
        long max = a;
        if(a < b)
            max = b;

        for(int i = 2; i*i <= max ; i++){
            if(a % i == 0 && b % i == 0)
                count += 1;
            while(a % i == 0){
                a /= i;
            }
            while(b % i == 0){
                b /= i;
            }
        }
        System.out.println(count+1);
    }
}


package antbook.p0;

import java.util.Scanner;

public class Main {

    long a;
    long b;

    Main(long a, long b) {
        this.a = a;
        this.b = b;
    }

    /**
     *
     * @return greeting message
     */
    public int solve() {

        // max integer requred
        int UPPER_BOUND = (int) (Math.sqrt(Math.max(a, b)));

        // prime sieve
        boolean[] isPrime = new boolean[UPPER_BOUND];

        // prime list
        int[] plist = new int[UPPER_BOUND];

        isPrime[0] = false;
        isPrime[1] = false;
        for (int i = 2; i < UPPER_BOUND; i++) {
            isPrime[i] = true;
        }

        int c = 0;
        for (int i = 2; i < UPPER_BOUND; i++) {
            if (isPrime[i]) {
                plist[c++] = i;
                for (int j = i * 2; j < UPPER_BOUND; j += i) {
                    isPrime[j] = false;
                }
            }
        }

        int ans = 1;

        for (int i = 0; i < c; i++) {
            if (a % plist[i] == 0 && b % plist[i] == 0) {
                ans++;
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        // input
        Scanner sc = new Scanner(System.in);
        long a = sc.nextLong();
        long b = sc.nextLong();
        sc.close();

        // solve
        int p = new Main(a, b).solve();

        // display
        System.out.println(p);
    }

}


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

public class Main
{
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok;

    public void go() throws IOException
    {
        boolean[] isPrime = new boolean[1001000];
        Arrays.fill(isPrime, true);
        isPrime[0] = false;
        isPrime[1] = false;
        for (int i = 2; i < isPrime.length; i++)
        {
            if (!isPrime[i])
            {
                continue;
            }
            for (int j = i*2; j < isPrime.length; j += i)
            {
                isPrime[j] = false;
            }
        }
        int p = 0;
        int[] primes = new int[100000];
        for (int i = 0; i < isPrime.length; i++)
        {
            if (isPrime[i])
            {
                primes[p] = i;
                p++;
            }
        }

        ntok();
        long a = lpar();
        long b = lpar();
        long gcd = gcd(a, b);
        // out.println(gcd);
        long count = 0;
        HashSet<Long> set = new HashSet<>();
        long[] freq = new long[100000];
        for (int i = 0; i < p; i++)
        {
            while (gcd % primes[i] == 0)
            {
                freq[i]++;
                count++;
                set.add((long)primes[i]);
                gcd /= primes[i];
            }
        }
        set.add(1L);
        set.add(gcd);
        long sum = count * (count + 1) / 2;
        for (int i = 0; i < freq.length; i++)
        {
            sum -= freq[i] * (freq[i]-1) / 2;
        }
        out.println(set.size());

        out.flush();
        in.close();
    }

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

    public void ntok() throws IOException
    {
        tok = new StringTokenizer(in.readLine());
    }

    public int ipar()
    {
        return Integer.parseInt(tok.nextToken());
    }

    public int[] iapar(int n)
    {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++)
        {
            arr[i] = ipar();
        }
        return arr;
    }

    public long lpar()
    {
        return Long.parseLong(tok.nextToken());
    }

    public long[] lapar(int n)
    {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++)
        {
            arr[i] = lpar();
        }
        return arr;
    }

    public double dpar()
    {
        return Double.parseDouble(tok.nextToken());
    }

    public String spar()
    {
        return tok.nextToken();
    }

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


import java.util.*;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc=new Scanner(System.in);
		String s=sc.next();

		String s1="Sunny";
		String s2="Cloudy";
		String s3="Rainy";
		if(s.equals(s1)){
			System.out.println(s2);
		}else if(s.equals(s2)){
			System.out.println(s3);
		}else
			System.out.println(s1);

	}

}

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


import java.util.*;

public class Main {
  public static void main(String[] args ) throws Exception {
    Scanner sc = new Scanner(System.in);
    String N = sc.next();
    if(N.equals("Sunny")){
    	System.out.println("Cloudy");
    }else if(N.equals("Cloudy")){
    	System.out.println("Rainy");
    }else{
    	System.out.println("Sunny");
    }
  }
}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int participants = sc.nextInt();  //参加者数
		int point = sc.nextInt();  //ポイント
		int questions = sc.nextInt();  //問題数
		int winner[] = new int[questions];  //問題ごとに正解した人の番号

		//問題ごとに正解した参加者の番号を代入
		for(int i : winner) {
			winner[i] = sc.nextInt();
		}

		//「要素番号=参加者番号」の配列に得点を入れる
		int result[] = new int[participants];
		for(int i : result) {
			result[i] = point;
		}

		//問題ごとに正解してない参加者番号の人のポイントから-1
		for(int i : winner) {
			for(int j : result) {
				if(winner[i] != j) {
					result[j] -=1;
				}
			}
		}

		for(int i : result) {
		System.out.println(result[i] > 0 ? "Yes" : "No");
		}
	}
}

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


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

public class Main {
    public static void main(String[] args) {
        FastReader sc = new FastReader(System.in);
        System.out.println((int)Math.pow(sc.nextInt(), 3));
    }
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;
        public FastReader(InputStream x) {
            br = new BufferedReader(new
                    InputStreamReader(x));

        }

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

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


import java.util.Scanner;

public class Main {
    static final Scanner sc = new Scanner(System.in);
    static final int MOD = (int) 1E9 + 7;

    public static void main(String[] args) {
        int N = nint();
        int[] A = nints(N, 1, 0);
        int[] B = nints(N, 1, 0);
        int[] C = nints(N-1, 1, 0);
        int ans = 0;

        for (int i = 1; i <= N; i++) {
            ans += B[A[i]];
            if (i > 1 && A[i] == A[i-1] + 1) {
                ans += C[A[i-1]];
            }
        }
        System.out.println(ans);
    }

    private static long nlong() {
        return sc.nextLong();
    }

    private static int nint() {
        return sc.nextInt();
    }

    private static String nstr() {
        return sc.next();
    }

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

    private static int[] nints(int n) {
        return nints(n, 0, 0);
    }

    private static int[] nints(int n, int padL, int padR) {
        int[] a = new int[padL + n + padR];
        for (int i = 0; i < n; i++)
            a[padL + i] = nint();
        return a;
    }

    private static char[][] nchars2(int h, int w) {
        return nchars2(h, w, 0);
    }

    private static char[][] nchars2(int h, int w, int pad) {
        char[][] a2 = new char[h + pad * 2][w + pad * 2];
        for (int i = 0; i < h; i++)
            System.arraycopy(nchars(), 0, a2[pad + i], pad, w);
        return a2;
    }
}

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


import java.io.PrintWriter;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = Integer.parseInt(sc.next());
        int[] B = new int[N - 1];
        int A = 0;

        for (int i = 0; i < N - 1; i++) {
            B[i] = Integer.parseInt(sc.next());
        }

        A += B[0];
        for (int i = 1; i < N - 1; i++) {
            A += Math.min(B[i - 1], B[i]);
        }
        A += B[N - 2];

        PrintWriter out = new PrintWriter(System.out);
        out.println(A);

        sc.close();
        out.flush();
    }
}

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        int[] aryb = new int[n - 1];
        int ans = 0;
        for (int i = 0; i < n - 1; i++) {
            int a = Integer.parseInt(sc.next());
            aryb[i] = a;
        }
        for (int i = n - 2; i >= 0; i--) {
            if (i == n - 2) {
                ans += aryb[i];
            }
            if (i == 0) {
                ans += aryb[i];
            } else {
                ans += Math.min(aryb[i], aryb[i - 1]);
            }
        }
        System.out.println(ans);
    }
}


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

public class Main implements Runnable {
	FastReader scn;
	PrintWriter out;
	String INPUT = "";

	void solve() {
		int n = scn.nextInt();
		int[] arr = new int[n + 2];
		for (int i = 1; i <= n; i++) {
			arr[i] = scn.nextInt();
		}
		arr[n + 1] = (int) 1e6;

		n++;
		int[] st = new int[n + 1], left = new int[n + 1], right = new int[n + 1];

		int top = -1;
		for (int i = 1; i <= n; i++) {
			while (top != -1 && arr[st[top]] < arr[i]) {
				top--;
			}
			left[i] = top == -1 ? 0 : st[top];
			st[++top] = i;
		}

		top = -1;
		for (int i = n; i > 0; i--) {
			while (top != -1 && arr[st[top]] < arr[i]) {
				top--;
			}
			right[i] = top == -1 ? n + 1 : st[top];
			st[++top] = i;
		}

		seg = new int[4 * n];
		build(1, 1, n, arr);

		long ans = 0;
		for (int i = 1; i < n; i++) {
			if (arr[i] == n - 1) {
				continue;
			}
			int lf = left[i], rt = right[i];

			long sub = 0;

			// right part
			if (rt != n) {
				int x = i - lf, y;

				int rv = queryRight(1, 1, n, rt + 1, right[rt], arr[i]);
				y = Math.max(1, rv - rt);

				sub += x * 1L * y;
			}

			// left part
			if (lf != 0) {
				int x = rt - i, y;

				int rv = queryLeft(1, 1, n, left[lf], lf - 1, arr[i]);
				y = Math.max(1, lf - rv);

				sub += x * 1L * y;
			}

			ans += sub * arr[i];
		}

		out.println(ans);
	}

	int[] seg;

	int queryLeft(int ind, int l, int r, int si, int li, int val) {
		if (l > li || r < si || l > r) {
			return (int) 0;
		}

		if (l == r) {
			if (seg[ind] > val)
				return l;
			return 0;
		}

		int m = (l + r) >> 1;
		if (l >= si && r <= li) {
			if (seg[2 * ind + 1] > val) {
				return queryLeft(2 * ind + 1, m + 1, r, si, li, val);
			} else {
				return queryLeft(2 * ind, l, m, si, li, val);
			}
		}

		int a = queryLeft(2 * ind, l, m, si, li, val);
		int b = queryLeft(2 * ind + 1, m + 1, r, si, li, val);

		return Math.max(a, b);
	}

	int queryRight(int ind, int l, int r, int si, int li, int val) {
		if (l > li || r < si || l > r) {
			return (int) 1e6;
		}

		if (l == r) {
			if (seg[ind] > val)
				return l;
			return (int) 1e6;
		}

		int m = (l + r) >> 1;
		if (l >= si && r <= li) {
			if (seg[2 * ind] > val) {
				return queryRight(2 * ind, l, m, si, li, val);
			} else {
				return queryRight(2 * ind + 1, m + 1, r, si, li, val);
			}
		}

		int a = queryRight(2 * ind, l, m, si, li, val);
		int b = queryRight(2 * ind + 1, m + 1, r, si, li, val);

		return Math.min(a, b);
	}

	void build(int ind, int l, int r, int[] arr) {
		if (l == r) {
			seg[ind] = arr[l];
			return;
		}
		int m = (l + r) >> 1;
		build(2 * ind, l, m, arr);
		build(2 * ind + 1, m + 1, r, arr);
		seg[ind] = Math.max(seg[2 * ind], seg[2 * ind + 1]);
	}

	public void run() {
		long time = System.currentTimeMillis();
		boolean oj = true;
		out = new PrintWriter(System.out);
		scn = new FastReader(oj);
		solve();
		out.flush();
		if (!oj) {
			System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
		}
	}

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

	class FastReader {
		InputStream is;

		public FastReader(boolean onlineJudge) {
			is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		}

		public FastReader() {
			is = System.in;
		}

		byte[] inbuf = new byte[1024];
		public int lenbuf = 0, ptrbuf = 0;

		int readByte() {
			if (lenbuf == -1)
				throw new InputMismatchException();
			if (ptrbuf >= lenbuf) {
				ptrbuf = 0;
				try {
					lenbuf = is.read(inbuf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return -1;
			}
			return inbuf[ptrbuf++];
		}

		boolean isSpaceChar(int c) {
			return !(c >= 33 && c <= 126);
		}

		int skip() {
			int b;
			while ((b = readByte()) != -1 && isSpaceChar(b))
				;
			return b;
		}

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

		char nextChar() {
			return (char) skip();
		}

		String next() {
			int b = skip();
			StringBuilder sb = new StringBuilder();
			while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		String nextLine() {
			int b = skip();
			StringBuilder sb = new StringBuilder();
			while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		char[] next(int n) {
			char[] buf = new char[n];
			int b = skip(), p = 0;
			while (p < n && !(isSpaceChar(b))) {
				buf[p++] = (char) b;
				b = readByte();
			}
			return n == p ? buf : Arrays.copyOf(buf, p);
		}

		int nextInt() {
			int num = 0, b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

		long nextLong() {
			long num = 0;
			int b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

		char[][] nextMatrix(int n, int m) {
			char[][] map = new char[n][];
			for (int i = 0; i < n; i++)
				map[i] = next(m);
			return map;
		}

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

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

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

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

		long[][] next2DLong(int n, int m) {
			long[][] arr = new long[n][];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLongArray(m);
			}
			return arr;
		}

		int[] shuffle(int[] arr) {
			Random r = new Random();
			for (int i = 1, j; i < arr.length; i++) {
				j = r.nextInt(i);
				int c = arr[i];
				arr[i] = arr[j];
				arr[j] = c;
			}
			return arr;
		}

		long[] shuffle(long[] arr) {
			Random r = new Random();
			for (int i = 1, j; i < arr.length; i++) {
				j = r.nextInt(i);
				long c = arr[i];
				arr[i] = arr[j];
				arr[j] = c;
			}
			return arr;
		}

		int[] uniq(int[] arr) {
			arr = scn.shuffle(arr);
			Arrays.sort(arr);
			int[] rv = new int[arr.length];
			int pos = 0;
			rv[pos++] = arr[0];
			for (int i = 1; i < arr.length; i++) {
				if (arr[i] != arr[i - 1]) {
					rv[pos++] = arr[i];
				}
			}
			return Arrays.copyOf(rv, pos);
		}

		long[] uniq(long[] arr) {
			arr = scn.shuffle(arr);
			Arrays.sort(arr);
			long[] rv = new long[arr.length];
			int pos = 0;
			rv[pos++] = arr[0];
			for (int i = 1; i < arr.length; i++) {
				if (arr[i] != arr[i - 1]) {
					rv[pos++] = arr[i];
				}
			}
			return Arrays.copyOf(rv, pos);
		}

		int[] reverse(int[] arr) {
			int l = 0, r = arr.length - 1;
			while (l < r) {
				arr[l] = arr[l] ^ arr[r];
				arr[r] = arr[l] ^ arr[r];
				arr[l] = arr[l] ^ arr[r];
				l++;
				r--;
			}
			return arr;
		}

		long[] reverse(long[] arr) {
			int l = 0, r = arr.length - 1;
			while (l < r) {
				arr[l] = arr[l] ^ arr[r];
				arr[r] = arr[l] ^ arr[r];
				arr[l] = arr[l] ^ arr[r];
				l++;
				r--;
			}
			return arr;
		}

		int[] compress(int[] arr) {
			int n = arr.length;
			int[] rv = Arrays.copyOf(arr, n);
			rv = uniq(rv);
			for (int i = 0; i < n; i++) {
				arr[i] = Arrays.binarySearch(rv, arr[i]);
			}
			return arr;
		}

		long[] compress(long[] arr) {
			int n = arr.length;
			long[] rv = Arrays.copyOf(arr, n);
			rv = uniq(rv);
			for (int i = 0; i < n; i++) {
				arr[i] = Arrays.binarySearch(rv, arr[i]);
			}
			return arr;
		}
	}
}

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136