import java.util.*;

public class Main {

	public static void main(String[] args) {

		Scanner keyboard = new Scanner(System.in);

		long N = keyboard.nextLong();
		long P = keyboard.nextLong();

		HashMap<Long, Integer> prime = new HashMap<Long, Integer>();
		for (int i=2;1L*i*i<=P;i++) {
			while (P % i == 0) {
				int count = prime.containsKey((long)i) ? prime.get((long)i) : 0;
				prime.put((long)i, count + 1);
				P /= i;
			}
		}
		if (P != 1) prime.put(P, 1);

		long ans = 1;
        for (Map.Entry<Long, Integer> entry : prime.entrySet()) {
            for (int i=0; i < entry.getValue() / N; i++) {
        		ans *= entry.getKey();
        	}
        }

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

}

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    boolean allEven = true;
    for (int i = 0; i < N; i++) {
      int a = sc.nextInt();
      if (a%2 != 0) {
        allEven = false;
      }
    }
    System.out.println(allEven ? "second" : "first");
  }
}

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

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second

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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;

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

    static class BPowersOfTwo {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            // input
            int n = in.nextInt();
            ArrayList<Integer> a = new ArrayList<>();
            int ans = 0;
            for (int i = 0; i < n; i++) {
                a.add(in.nextInt());
            }
            a.sort(Comparator.naturalOrder());
            while (a.size() > 1) {
                // 二分探索で一つ上のを探す
                // 一回当たりlogNだから全体で N*logN が上界
                int target = 1;
                while (target <= a.get(a.size() - 1)) {
                    target *= 2;
                }
                target -= a.get(a.size() - 1);

                a.remove(a.size() - 1);

                // System.out.println("size: " + a.size() + ", target: " + target);
                // targetを二分探索で探す
                int low = 0;
                int high = a.size() - 1;
                int mid = (low + high) / 2;
                while (high >= low) {
                    boolean f = false;
                    if (a.get(mid) < target) {
                        //System.out.println("low");
                        low = mid + 1;
                    } else if (a.get(mid) > target) {
                        //System.out.println("high");
                        high = mid - 1;
                    } else {
                        f = true;
                        // System.out.println("got it");
                        ans++;
                        a.remove(mid);
                    }
                    mid = (low + high) / 2;
                    if (f) break;
                }
            }

            out.println(ans);

        }

    }
}

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


import java.util.Scanner;

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

    public static void solve(Scanner sc) {
        int n = sc.nextInt();
        sc.nextLine();
        String[] aStrings = sc.nextLine().split(" ");
        int[] as = new int[n];
        for (int i = 0; i < n; i++) {
            as[i] = Integer.parseInt(aStrings[i]);
        }

        int count = 0;
        for (int i = 0; i < n; i++) {
            if (as[i] == 1) {
                count++;
            }
        }
        if (as[0] != 1) {
            count++;
        }
        System.out.println(count);
    }
}

Score : 700 points

Problem Statement

There are N strings arranged in a row.
It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right.
That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left.

At least how many different characters are contained in S_1,S_2,...,S_N, if the length of S_i is known to be A_i?

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Note

The strings do not necessarily consist of English alphabet; there can be arbitrarily many different characters (and the lexicographic order is defined for those characters).

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of different characters contained in the strings.

Sample Input 1

3
3 2 1

Sample Output 1

2

The number of different characters contained in S_1,S_2,...,S_N would be 3 when, for example, S_1=abc, S_2=bb and S_3=c.

However, if we choose the strings properly, the number of different characters can be 2.

Sample Input 2

5
2 3 2 1 2

Sample Output 2

2


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

public class Main {
    private static int N;
    private static int K;
    private static int[] h;

    static {
        Scanner sc = new Scanner(System.in);
        N = Integer.parseInt(sc.next());
        K = Integer.parseInt(sc.next());
        h = new int[N];
        for (int i = 0; i < N; i++) {
            h[i] = Integer.parseInt(sc.next());
        }
    }

    public static void main(String[] args) {
        Arrays.sort(h);
        int res = Integer.MAX_VALUE;
        for (int i = 0; i <= N - K; i++) {
            res = Math.min(res, h[K + i - 1] - h[i]);
        }

        System.out.println(res);
    }
}

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


import java.util.Scanner;
public class Main {

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

          int X = sc.nextInt();
      if(X==7||X==5||X==3){
        System.out.println("Yes");
      }else{
		System.out.println("No");
      }
    }
}

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

	static final int[][] FN = new int[][]{ {74, 1, 1}, {24, 2, 1}, {14, 4, 1}, {4, 4, 2}};

	public static void main(String[] args) {
		Scanner sysin = new Scanner(System.in);
		final int n = sysin.nextInt();
		sysin.close();

		//System.out.println(String.format("  N    = %3d", n));
		int[] primes = getPrime(n);
		//System.out.println(Arrays.stream(primes).boxed().map(e -> String.format("%3d", e)).collect(Collectors.joining(",", "素数   = [", "] (2 ≦ P ≦ N)")));
		List<Result> primeFactors = getPrimeFactors(n, primes);
		//System.out.println(primeFactors.stream().map(Result::toString).collect(Collectors.joining(" * ", String.format("%3d!   = ", n), "")));
		List<Results> result = dp(primeFactors).stream().distinct().sorted(Comparator.comparingDouble(Results::getValue)).collect(Collectors.toList());
		//System.out.println(result.stream().mapToDouble(Results::getValue).mapToObj(e -> String.format("%.0f", e)).collect(Collectors.joining(", ", "75数   = [", "]")));
		//System.out.println(result.stream().map(Results::toString).collect(Collectors.joining(", ", "素因数 = [", "]")));
		//System.out.println(String.format("答え   = %d個", result.stream().mapToDouble(Results::getValue).count()));
		System.out.println(result.stream().mapToDouble(Results::getValue).count());
	}

	private static final List<Results> dp(List<Result> factors) {
		List<Results> result = new ArrayList<>();

		for (int[] nums : FN) {
			List<List<Result>> entries = new ArrayList<>();
			for (int i = 0; i < 3; i++) {
				final int min = nums[i];
				if (min > 1) {
					entries.add(factors.stream()
							.filter(r -> r.getE() >= min)
							.collect(Collectors.toList()));
				} else {
					entries.add(Arrays.asList(Result.NULL));
				}
			}

			for (Result x : entries.get(0)) {
				for (Result y : entries.get(1)) {
					if (y.equals(x)) continue;
					for (Result z : entries.get(2)) {
						if (z.equals(y) || z.equals(x)) continue;
						result.add(new Results(	new Result(x, nums[0]),
												new Result(y, nums[1]),
												new Result(z, nums[2]) ));
					}
				}
			}
		}

		return result;
	}

	// 2 ~ max までの素数の一覧を求める
	private static final int[] getPrime(int max) {
		List<Integer> primes = new ArrayList<>();

		outer : for (int i = 2; i <= max; i++) {
			for (int n : primes) {
				if (i % n == 0) {
					continue outer;
				}
			}
			primes.add(i);
		}

		return primes.stream().mapToInt(Integer::intValue).toArray();
	}

	// nを素因数分解し、素因数j:指数kのマッピングを返す
	private static final Map<Integer, Integer> countPrimeFactor(int n, int[] primes) {
		int i = 0;
		Map<Integer, Integer> primeFactors = new HashMap<>();

		while (n > 0 && n >= primes[i]) {
			if (n % primes[i] == 0) {
				n /= primes[i];

				Integer v = primeFactors.get(primes[i]);
				primeFactors.put(primes[i], (v == null) ? 1 : v + 1);
			} else {
				i++;
			}
		}

		return primeFactors;
	}

	// n!を素因数分解し、素因数j:指数kのマッピングを返す
	private static final List<Result> getPrimeFactors (int n, int[] primes) {

		Map<Integer, Integer> primeFactors = new HashMap<>();
		for (int i = 2; i <= n; i++) {
			Map<Integer, Integer> m = countPrimeFactor(i, primes);

			for(Entry<Integer, Integer> e : m.entrySet()) {
				Integer v = primeFactors.get(e.getKey());
				primeFactors.put(e.getKey(), e.getValue() + ((v == null) ? 0 : v));
			}
			System.out.println(m.entrySet().stream().map(e -> String.format("(%2d^%2d)", e.getKey(), e.getValue())).collect(Collectors.joining(" * ", String.format("%3d    = ", i), "")));
		}

		return primeFactors.entrySet().stream()
				.map(e -> new Result(e.getKey(), e.getValue()))
				.sorted(Comparator.comparingInt(Result::getB))
				.collect(Collectors.toList());
	}
}

class Result {
	static Result NULL;
	static { NULL = new Result(1, 1); }

	private final int B;
	private final int E;
	public Result(int base, int exponent) {
		B = base;
		E = exponent;
	}

	public Result(Result r, int exponent) {
		B = r.B;
		E = exponent;
	}

	private final double pow(int b, int e) {
		double r = 1;
		for (int i = 0; i < e; i++) {
			r *= b;
		}
		return r;
	}

	protected final double getR() {
		return pow(B, E);
	}

	protected final int getB() {
		return B;
	}

	protected final int getE() {
		return E;
	}

	protected final boolean isNotNull() {
		return getR() != 1;
	}

	@Override
	public String toString() {
		return String.format("(%2d^%2d)", B, E);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) return false;
		if (!(obj instanceof Result)) return false;

		Result r = (Result)obj;
		return (r.isNotNull() && this.isNotNull() && (r.getR() == this.getR()));
	}
}

class Results {
	private final List<Result> RS;
	private double V;

	public Results() {
		RS = new ArrayList<>();
		calc();
	}

	public Results(Result... r) {
		this();
		Arrays.stream(r).filter(Result::isNotNull).forEach(RS::add);
		calc();
	}

	private void calc() {
		V = RS.stream().mapToDouble(Result::getR).reduce(1, (e1, e2) -> e1 * e2);
	}

	public double getValue() {
		return V;
	}

	@Override
	public String toString() {
		return RS.stream().filter(Result::isNotNull).map(Result::toString).collect(Collectors.joining(" * ", "[", "]"));
	}

	@Override
	public boolean equals(Object e) {
		return (e instanceof Results) &&
				((Results)e).getValue() == this.getValue();
	}

	@Override
	public int hashCode() {
		return 0;
	}
}

class NullEntry implements Entry<Integer, Integer> {
	public NullEntry() {
	}

	@Override
	public Integer getKey() {
		return 1;
	}

	@Override
	public Integer getValue() {
		return 1;
	}

	@Override
	public Integer setValue(Integer value) {
		return 1;
	}

	@Override
	public boolean equals(Object e) {
		return false;
	}
}

Score : 400 points

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


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

public class Main {

    int N;

    private void solve() {
        // 36400 = 2 * 2 * 2 * 2 * 3 * 3 * 3 * 3 * 5 * 5
        // 75 = 3 * 5 * 5, 5 * 15, 25 * 3, 75
        N = nextInt();
        int[] primeFactor = new int[101];

        int sum = 1;
        for(int i = 1;i <= N;i++) {
            sum *= i;

            for(int j = 2;j * j <= sum;j++) {
                while(sum % j == 0) {
                    primeFactor[j]++;
                    sum /= j;
                }
            }

            if (sum > 1) {
                primeFactor[sum]++;
                sum = 1;
            }
        }

        int ans = 0;
        for(int i = 1;i <= 98;i++) {
            for(int j = i + 1; j <= 99;j++) {
                for(int k = j + 1;k <= 100;k++) {
                    if (primeFactor[i] >= 2 && primeFactor[j] >= 4 && primeFactor[k] >= 4) {
                        ans++;
                    }

                    if (primeFactor[j] >= 2 && primeFactor[i] >= 4 && primeFactor[k] >= 4) {
                        ans++;
                    }

                    if (primeFactor[k] >= 2 && primeFactor[i] >= 4 && primeFactor[j] >= 4) {
                        ans++;
                    }
                }
            }
        }

        for(int i = 1;i <= 99;i++) {
            for(int j = i + 1;j <= 100;j++) {
                if (primeFactor[i] >= 14 && primeFactor[j] >= 4) {
                    ans++;
                }

                if (primeFactor[j] >= 15 && primeFactor[i] >= 4) {
                    ans++;
                }

                if (primeFactor[i] >= 24 && primeFactor[j] >= 2) {
                    ans++;
                }

                if (primeFactor[j] >= 24 && primeFactor[i] >= 2) {
                    ans++;
                }
            }
        }

        for(int i = 1;i <= 100;i++) {
            if (primeFactor[i] >= 74) {
                ans++;
            }
        }

        out.println(ans);
    }

    public static void main(String[] args) {
        out.flush();
        new Main().solve();
        out.close();
    }

    /* Input */
    private static final InputStream in = System.in;
    private static final PrintWriter out = new PrintWriter(System.out);
    private final byte[] buffer = new byte[4096];
    private int p = 0;
    private int buflen = 0;

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

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

    private boolean isPrint(int ch) {
        if (ch >= '!' && ch <= '~')
            return true;
        return false;
    }

    private int nextByte() {
        if (!hasNextByte())
            return -1;
        return buffer[p++];
    }

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

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

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

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


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner sc=new Scanner(System.in);
        int train=sc.nextInt();
        int bus=sc.nextInt();
        int sum=train+bus/2;
        System.out.println(sum);
    }
}

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;

class Main {

    static final int MOD = 1000000007;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int T = sc.nextInt();
        int A = sc.nextInt();
        double[] hei = new double[N];
        int sum = 0;
        for (int i = 0; i < N; i++) {
            hei[i] = Math.abs(A-(T-sc.nextInt()*0.006));
        }
        double min = Double.MAX_VALUE;
        int c = -1;
        for (int i = 0; i < N; i++) {
            if(min>hei[i]){
                min=hei[i];
                c=i;
            }
        }
        System.out.println(c+1);

    }
}

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


import java.util.*;

public class Main {

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int t = sc.nextInt();
		int a = sc.nextInt();
		int min = 0;
		int min_value = Integer.MAX_VALUE;
		for (int i = 0 ; i < n; i++) {
			int tmp = sc.nextInt();
			if (tmp < min_value) {
				min_value = tmp;
				min = i + 1;
			}
		}
		System.out.println(min);
	}

}


import java.util.Scanner;
public class Main{
	public static void main(String[] argv){
		Scanner scan = new Scanner(System.in);
		palace(scan);
	}
	public static void palace(Scanner scan){
		//入力値の中で，最もAに近いもののインデックスを出力
		int N = scan.nextInt();
		int T = scan.nextInt(); int A = scan.nextInt();
		int in = scan.nextInt();
		int index = 1;
		double min = Math.abs(A-T+0.006*in);
		for(int i=2;i<=N;i++){
			in = scan.nextInt();
			double dif = Math.abs(A-T+0.006*in);
			if(min>dif){
				min = dif;
				index = i;
			}
		}
		System.out.println(index);
	}
}


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

public class Main {

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

		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int [] City1=new int[M];
		int [] City2=new int[M];
		int []tag = new int[N];

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

		for(int i=0;i<M;i++) {
			City1[i]=sc.nextInt();
			City2[i]= sc.nextInt();
			map.put(City2[i], i);

		}
		int y=0;
		int z=0;
		for(Integer key : map.keySet()){
			y=map.get(key);
			z = City1[y];
			if(tag[z-1]!=0) {
				City2[y]=tag[z-1];
				tag[z-1]=tag[z-1]+1;
				}else {
					tag[z-1]=1;
					City2[y]=tag[z-1];
					tag[z-1]=tag[z-1]+1;
				}
	      }
		for(int i=0;i<M;i++) {
			String str1 = String.format("%06d", City1[i]);
			String str2 = String.format("%06d", City2[i]);
			System.out.println(str1+str2);
		}

		sc.close();
	}

}

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


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

public class Main {

  class ID implements Comparable<ID> {
    int index;
    int prefecture;
    int year;
    String id;

    public ID(int index, int prefecture, int year) {
      this.index = index;
      this.prefecture = prefecture;
      this.year = year;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      ID id1 = (ID) o;
      return index == id1.index &&
              prefecture == id1.prefecture &&
              year == id1.year &&
              Objects.equals(id, id1.id);
    }

    @Override
    public int hashCode() {
      return Objects.hash(index, prefecture, year, id);
    }

    @Override
    public int compareTo(ID o) {
      return this.year - o.year;
    }
  }

  private void solve(InputReader in, PrintWriter out) {
    int n = in.nextInt();
    int m = in.nextInt();
    ArrayList<ID> list = new ArrayList<>();
    int arr[] = new int[n + 1];
    for (int i = 0; i < m; i++) {
      int index = in.nextInt();
      list.add(new ID(i, index, in.nextInt()));
      arr[index]++;
    }
    int[] tmp = new int[n + 1];
    if (n + 1 >= 0) System.arraycopy(arr, 0, tmp, 0, n + 1);
    Collections.sort(list);
    for (int i = 0; i < m; i++) {
      list.get(i).id = String.valueOf(arr[list.get(i).prefecture] + 1 - tmp[list.get(i).prefecture]--);
    }
    list.sort(Comparator.comparingInt(a -> a.index));
    for (int i = 0; i < m; i++) {
      StringBuilder val = new StringBuilder(String.valueOf(list.get(i).prefecture));
      StringBuilder val2 = new StringBuilder(String.valueOf(list.get(i).id));
      int len = val.length();
      int len2 = val2.length();
      if (val.length() < 6) {
        for (int j = 0; j < 6 - len; j++) {
          val.insert(0, "0");
        }
      }
      if (val2.length() < 6) {
        for (int j = 0; j < 6 - len2; j++) {
          val2.insert(0, "0");
        }
      }
      out.println(val.toString() + val2.toString());
    }

  }

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

  private void run() throws FileNotFoundException {

    //new FileInputStream(new File("input.txt"))
    //
    try (InputReader in = new InputReader(System.in);
         PrintWriter out = new PrintWriter(System.out)) {
      solve(in, out);
    }
  }

  static class InputReader implements AutoCloseable {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

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

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

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

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

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

    @Override
    public void close() {
    }
  }

}


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		long N = sc.nextInt();
		long M = sc.nextInt();
		char[] S = sc.next().toCharArray();
		char[] T = sc.next().toCharArray();
		long g = gcd(N,M);
		long L = (N * M) / g;
		boolean flag = true;

		for(long i = 0;i<g;i++) {
			if(S[(int)(N/g * i)] != T[(int)(M/g *i)]) {
				flag = false;
			}
		}

		if(flag) {
			System.out.println(L);
		}else {
			System.out.println("-1");
		}
	    sc.close();
	}

    private static long gcd(long m, long n) {
        if(m < n) return gcd(n, m);
        if(n == 0) return m;
        return gcd(n, m % n);
    }

}

Score : 300 points

Problem Statement

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long m = sc.nextLong();
        String s = sc.next();
        String t = sc.next();
        long seki = lcm(n, m);
        long NL = seki / n;
        long ML = seki / m;

        int sCount = 0;
        int tCount = 0;
        long ss = 0;
        long tt = 0;
        boolean flag = true;
        for(long i = 0;i < seki;i += Math.min(NL,ML)){
            if(ss == tt){
                if(s.charAt(sCount) != t.charAt(tCount)){
                    flag = false;
                }
                sCount++;
                tCount++;
                ss += NL;
                tt += ML;
            }else if(ss < tt){
                sCount++;
                ss += NL;
            }else{
                tCount ++;
                tt += ML;
            }
            if(ss >= seki)break;
            if(tt >= seki)break;

        }
        if(flag){
            System.out.println(seki);
        }else{
            System.out.println(-1);
        }

    }

    private static long lcm(long m, long n) {
        return m * n / gcd(m, n);
    }

    private static long gcd(long m, long n) {
        if (m < n)
            return gcd(n, m);
        if (n == 0)
            return m;
        return gcd(n, m % n);
    }
}


import java.util.Scanner;

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

        if (sc.nextInt() == 1) {
            System.out.println("Hello World");
        } else {
            System.out.println(sc.nextInt() + sc.nextInt());
        }
        sc.close();
    }
}

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


import java.util.*;
public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int t = sc.nextInt();
    int cost = sc.nextInt();
    int time = sc.nextInt();
    for(int i=0; i<n-1; i++){
      int c1 = sc.nextInt();
      int t1 = sc.nextInt();
      if(t1 < time){
         cost = c1;
         time = t1;
      }
    }
    if(time > t)
      System.out.println("TLE");
    else
      System.out.println(cost);
  }
}

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		String t = "";
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c == '1') {
				t += "9";
			}
			if (c == '9') {
				t += "1";
			}
		}
		System.out.println(t);
	}
}

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


import java.util.Scanner;

public class Main implements Runnable {

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

    public static void main(String[] args) {
        new Thread(null, new Main(), "", 128 * 1024 * 1024).start();
    }

    public void run() {
        int n = sc.nextInt();
        while (true) {
            String s = String.valueOf(n);
            char c = s.charAt(0);
            boolean f = true;
            for (int i = 1; i < s.length(); i++) {
                if (c != s.charAt(i)) {
                    f = false;
                    break;
                }
            }
            if(f){
                break;
            }
            n++;
        }
        System.out.println(n);
    }
}

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        int[] v = new int[n];
        Map<Integer, Integer> ki = new HashMap<>();
        Map<Integer, Integer> gu = new HashMap<>();
        for(int i=0; i<n; i++) {
            v[i] = Integer.parseInt(sc.next());
            if(i % 2 == 1) {
                if(ki.containsKey(v[i])) ki.put(v[i], ki.get(v[i])+1);
                else ki.put(v[i], 1);
            }else {
                if(gu.containsKey(v[i])) gu.put(v[i], gu.get(v[i])+1);
                else gu.put(v[i], 1);
            }
        }
        ki.put(0, 0);
        gu.put(0, 0);
        int kimax = 0;
        int gumax = 0;
        int kisemax = 0;
        int gusemax = 0;
        for(int key : ki.keySet()) {
            if(kimax < ki.get(key)) kimax = key;
        }
        for(int key : ki.keySet()) {
            if(key == kimax) continue;
            if(kisemax < ki.get(key)) kisemax = key;
        }
        for(int key : gu.keySet()) {
            if(gumax < gu.get(key)) gumax = key;
        }
        for(int key : gu.keySet()) {
            if(key == gumax) continue;
            if(gumax < gu.get(key)) gusemax = key;
        }
        if(kimax == gumax) System.out.println(n - max(ki.get(kimax)+gu.get(gusemax), ki.get(kisemax)+gu.get(gumax)));
        else System.out.println(n - ki.get(kimax) - gu.get(gumax));

    }
    public static int min(int a, int b) {
        if(a <= b) return a;
        else return b;
    }
    public static int max(int a, int b) {
        if(a <= b) return b;
        else return a;
    }
}

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


import java.util.Comparator;
import java.util.stream.IntStream;

public class Main {
    private static java.util.Scanner scanner = new java.util.Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        int[] u1 = new int[n / 2], u2 = new int[n / 2], count1 = new int[100001], count2 = new int[100001];
        for (int i = 0; i < n / 2; i++) {
            count1[u1[i] = scanner.nextInt()]++;
            count2[u2[i] = scanner.nextInt()]++;
        }

        int max1 = IntStream.range(0, 100001)
                .boxed()
                .max(Comparator.comparingInt(i -> count1[i]))
                .orElse(0);
        int max2 = IntStream.range(0, 100001)
                .boxed()
                .max(Comparator.comparingInt(i -> count2[i]))
                .orElse(0);
        if (max1 == max2) {
            int next1 = IntStream.range(0, 100001)
                    .filter(i -> i != max1)
                    .boxed()
                    .max(Comparator.comparingInt(i -> count1[i]))
                    .orElse(0);
            int next2 = IntStream.range(0, 100001)
                    .filter(i -> i != max2)
                    .boxed()
                    .max(Comparator.comparingInt(i -> count2[i]))
                    .orElse(0);
            System.out.println(n - Math.max(count1[next1] + count2[max2], count1[max1] + count2[next2]));
        } else {
            System.out.println(n - count1[max1] - count2[max2]);
        }
    }
}


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();
        int x = sc.nextInt();
        int a[] = new int[n];
        for(int i = 0; i < n; i++){
            a[i] = sc.nextInt();
        }
        Arrays.sort(a);
        int sum = 0;
        int count = 0;
        for(int i = 0; i < n; i++){
            sum += a[i];
            if (sum > x) {
                break;
            }else{
                count++;
            }
        }
        if (count == n && sum != x) {
            System.out.println(count - 1);
        }else{
            System.out.println(count);
        }
    }
}

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


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

public class Main {

    class A {
        int a;
        int b;

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

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            A a1 = (A) o;
            return a == a1.a &&
                    b == a1.b;
        }

        @Override
        public int hashCode() {
            return Objects.hash(a, b);
        }
    }

    private void solve(InputReader in, PrintWriter out) {
        int x1 = in.nextInt();
        int y1 = in.nextInt();
        int x2 = in.nextInt();
        int y2 = in.nextInt();
        int x3 = x1 - (y2 - y1);
        int y3 = y1+(x2-x1);
        int x4 = x2 - (y2 - y1);
        int y4 = y2+(x2-x1);
        out.println(x4 + " " + y4 + " " + x3 + " " + y3);
    }

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

    private void run() {
        try (
                InputReader in = new InputReader(System.in);
                PrintWriter out = new PrintWriter(System.out)) {
            solve(in, out);
        }
    }

    static class InputReader implements AutoCloseable {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

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

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

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

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

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

        @Override
        public void close() {

        }
    }

}

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


import java.util.Scanner;

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

		int x1 = scan.nextInt();
		int y1 = scan.nextInt();
		int x2 = scan.nextInt();
		int y2 = scan.nextInt();

		int X = x2 - x1;
		int Y = y2 - y1;

		int x3 = x2 - Y;
		int y3 = y2 + X;
		int x4 = x3 - X;
		int y4 = y3 - Y;

		System.out.println(x3 + " " + y3 + " " + x4 + " " + y4);

	}
}


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 ans = 0;

		for (int x = 1; x <= n; x++) {
			for (int y = 1; y <= n; y++) {
				for (int z = 1; z <= n; z++) {
					if ((x + y) % k == 0 && (y + z) % k == 0 && (z + x) % k == 0) {
						ans++;
					}
				}
			}
		}

		System.out.println(ans);

		sc.close();
	}
}

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191


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

        int N = sc.nextInt();
        int K = sc.nextInt();

        int ans = 0;

        if( K > 2 * N){
            ans = 0;
        }
        else if (K > N){
            ans = 1;
        }
 /*       if(K > N){
            if(K % 2 == 1){
                ans = 0;
            }
            else{
                K /= 2;
                if(K > N){
                    ans = 0;
                }
                else{
                    ans = (3 * N - 3 * K + 1) * (3 * N - 3 * K + 2) / 2;
                }
            }
        }*/
        else if(K % 2 == 0){
            K /= 2;
            int KK = N/K;
            ans += (int) Math.pow((KK/2), 3) + (int) Math.pow( ( ( KK + 1 ) / 2 ), 3);
        }
        else if(K % 2 == 1){
            ans += (int) Math.pow( (N/K) , 3);
        }
        System.out.println(ans);
    }
}


import java.util.Scanner;

public class Main {

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

		    //a+b,b+c,c+aがkの倍数ということはmodK=0となるということ。
		    //とりあえずNとKを読み込む
		    int N = scanner.nextInt();
		    int K = scanner.nextInt();
		    int n = N / K;
		    int kotae = n*(n-1)*(n-2)
					+n*(n-1)*3
					+n;

		    if( K % 2 != 0)
		    {
		    	System.out.println(kotae);
		    }
		    else
		    {
		    	if(N % K == 0)
		    	{
		    		System.out.println(kotae*2);
		    	}
		    	else {
		    		if( K / 2 <= N % K  )
		    		{
		    			int kotae2 = (n+1)*n*(n-1)+3*(n+1)*n+n+1;
		    			System.out.println(kotae+kotae2);
		    		}
		    		else
		    		{
		    		System.out.println(2*kotae);
		    		}
		    	}
		    }

		    scanner.close(); }
		  }


import java.util.Scanner;

public class Main {

	static Scanner scanner;

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

	    int n=gi();
	    int k=gi();

        System.out.println(n-k+1);
//        if (n%k==0) {
//        	System.out.print(0);
//        }else {
//        	System.out.print(1);
//        }

	}

	// 文字列として入力を取得
	public static String gs() {
		return scanner.next();
	}

	// intとして入力を取得
	public static int gi() {
		return Integer.parseInt(scanner.next());
	}

	// longとして入力を取得
	public static long gl() {
		return Long.parseLong(scanner.next());
	}

	// doubleとして入力を取得
	public static double gd() {
		return Double.parseDouble(scanner.next());
	}
}

Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


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

public class Main {

	static int N, K, Z = 0, F = 0;
	static int ANSWER = Integer.MAX_VALUE;
	static int[] DATA;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] lineArr = br.readLine().split(" ");
		N = Integer.parseInt(lineArr[0]);
		K = Integer.parseInt(lineArr[1]);

		DATA = new int[N];

		lineArr = br.readLine().split(" ");

		int tmp;
		for (int i = 0; i < N; i++) {
			DATA[i] = Integer.parseInt(lineArr[i]);
			tmp = Integer.parseInt(lineArr[i]);

			if (tmp < 0) {
				F++;
			} else if (tmp == 0) {
				Z++;
			}

			DATA[i] = tmp;
		}

		int start = 0;
		if (F > K) {
			start = F - K + Z;
		}

		int startValue;
		int endValue;
		for (int i = start; i < N - K + 1; i++) {
			startValue = DATA[i];
			endValue = DATA[i + K - 1];

			tmp = endValue - startValue;
			tmp += Math.min(Math.abs(startValue), Math.abs(endValue));

			if (ANSWER > tmp) {
				ANSWER = tmp;
			}
		}

		System.out.println(ANSWER);

	}
}

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

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

Sample Output 4

10


import java.util.*;

public class Main{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int a=sc.nextInt();
    int b=sc.nextInt();
    System.out.println((a-1)*(b-1));
  }
}

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


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

    if(n%2==0){
      System.out.println(0);
      return;
    }
	int ans = 0;
    int count = 0;
    for(int i = 1 ; i <= n ; ++i){
      if(n%i==0){
        count++;
      }
      if(i == n){
        if(count == 8){
          ans++;
          count = 0;
        }else{
          count = 0;
        }
      }

    }

    System.out.println(ans);

  }
}

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


import java.util.*;

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

		//Nまでの奇数をとる
		for (int i = 1; i <= N; i+=2) {
			//divを初期化
			int div = 0;
			//約数の計算
			for (int j = 1; j <= i; j++) {
				if(i%j == 0) {
					div++;
				}
			}
			//System.out.println(i + "の約数 : " + div + "個");

			//div==8のときのみ、countに追加
			if (div == 8) {
				count++;
			}
		}
		System.out.println(count);
	}
}


import java.util.Scanner;

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

		char[] S = sc.next().toCharArray();
		long K = sc.nextLong();
		for (int i = 0; i < S.length; i++) {
			if (S[i] != '1') {
				System.out.println(S[i]);
				break;
			}else {
				if (i == K) {
					System.out.println(S[i]);
					break;
				}
			}
		}

	}
}

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


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

public class Main {

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

	public void solve() throws IOException {
		FastScanner fs = new FastScanner();
		String s = fs.next();
		long k = fs.nextLong();

		for(int i = 0; i < s.length(); i++) {
			if(s.charAt(i) != '1') {
				System.out.println(s.charAt(i));
				return;
			}else {
				if(i == k-1) {
					System.out.println(1);
					return;
				}
			}
		}
	}

	public class FastScanner {

		BufferedReader reader;
		private StringTokenizer st;

		public FastScanner() {
			st = null;
			reader = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() throws IOException {
			if (st == null || !st.hasMoreElements()) {
				st = new StringTokenizer(reader.readLine());
			}
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			st = null;
			String readLine = null;
			readLine = reader.readLine();
			return readLine;
		}

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

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

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

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

		public void close() throws IOException {
			reader.close();
		}
	}

}


//https://atcoder.jp/contests/abc106/tasks/abc106_c

import java.io.*;

class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String S = br.readLine();
        String str = br.readLine();
        long K = Long.parseLong(str);
        String ans = "0";
        for (int i=0;i<K;i++){
            if (!String.valueOf(S.charAt(i)).equals("1")){
                ans = String.valueOf(S.charAt(i));
                break;
            }
        }
        if (ans.equals("0")){
            ans = "1";
        }
        System.out.println(ans);
    }
}


import java.util.Scanner;
import java.util.regex.*;
import java.math.*;

public class Main {

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		//int a = sc.nextInt();
		// スペース区切りの整数の入力
		//int b = sc.nextInt();
		//int c = sc.nextInt();
		// 文字列の入力
		//String s = sc.next();
		//1文字ずつ
		//s.atChar(i);
		// 出力
		//System.out.println("");
		//double countx=0;

		int N=sc.nextInt();
		int M=sc.nextInt();
		int Q=sc.nextInt();

		int[] L=new int[M];
		int[] R=new int[M];
		int[] p=new int[Q];
		int[] q=new int[Q];

		int[] ans=new int[Q];

		for(int i=0;i<M;i++){
			L[i]=sc.nextInt();
			R[i]=sc.nextInt();
		}

		for(int i=0;i<Q;i++){
			p[i]=sc.nextInt();
			q[i]=sc.nextInt();

			int count=0;

			for(int j=0;j<M;j++){
				if(p[i]<=L[j] && R[j]<=q[i]){
					count++;
				}

			}
			ans[i]=count;
		}

		for(int i=0;i<Q;i++){
			System.out.println(ans[i]);
		}

		System.exit(0);
	}
}

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

N is an integer between 1 and 500 (inclusive).

M is an integer between 1 and 200 \ 000 (inclusive).

Q is an integer between 1 and 100 \ 000 (inclusive).

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


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

class Main{

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		int M = scan.nextInt();

		long [] A = new long[N+1];

		for(int i= 1;i < N;i++){
			A[i] = A[i-1]+scan.nextInt();
		}

		Map<Long, Long> map = new HashMap<>();
		for(int i= 0;i<A.length;i++){
			map.put(A[i]%M, map.getOrDefault(A[i]%M, 0l)+1);
		}

		long  result = 0;
		for(long key:map.keySet()){					//mapのkeyを全て呼び出す
			long num = map.get(key);
			result+=(num*(num-1))/2;
		}

		System.out.println(result);
	}
}

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

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

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


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

        int N = scan.nextInt();
        int M = scan.nextInt();
        int[] Array = new int[N];
        int[][] table = new int[N][N];
        int count = 0;
        for(int i = 0; i < N; i++){
            Array[i] = scan.nextInt() % M;
            table[i][i] = Array[i];
        }
        for(int i = N-1; i >= 0; i--){
            for(int k = i; k >= 0; k--){
                if(k != i)
                    table[k][i] = (Array[k] + table[k+1][i])%M;
                if(table[k][i] == 0)count++;
            }
        }
        System.out.println(count);
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

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

            int difficulty = in.ni();
            long totalpts = in.nl();
            totalpts /= 100;
            int[] questions = new int[difficulty + 1];
            long[] bonuspts = new long[difficulty + 1];
            for (int i = 1; i <= difficulty; i++) {

                questions[i] = in.ni();
                bonuspts[i] = in.nl();
                bonuspts[i] /= 100;

            }
        /*
        out.println(difficulty+"  "+totalpts);
        out.println(questions);
        out.println(bonuspts);
        */
            long min = Long.MAX_VALUE;
            for (int i = difficulty; i >= 1; i--) {
                long sum = totalpts;
                long questionsolved = 0;

                for (int j = i; j >= 1; j--) {
                    if (sum <= 0)
                        break;
                    long ptsonquestion = bonuspts[j];
                    int ques = questions[j];
                    long quesreq = (sum + j - 1) / j;
                    if (quesreq >= ques) {
                        questionsolved += ques;
                        sum -= (ques * j + ptsonquestion);
                    } else {
                        questionsolved += (quesreq);
                        sum -= (quesreq * j);
                    }

                }
                if (sum <= 0) {
                    if (questionsolved < min)
                        min = questionsolved;
                }
            }

            out.println(min);

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

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

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

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

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

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

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

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

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

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

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

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

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

    }
}

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String s = sc.next();
    String head = s.substring(0,1);
    String last = s.substring(2,s.length()-1);
    int ch = 0;
    if(head.equals("A"))ch++;
    if(last.length() - last.replace("C","").length() == 1)ch++;
    if(ch != 2){
      System.out.println("WA");
      return;
    }
    last = last.replace("C","");
    String ALP[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    for(String al:ALP){
      if(last.contains(al) || s.substring(1,2).equals(al)){
        System.out.println("WA");
        return;
      }
    }
    System.out.println("AC");
  }
}

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    long N = 1_000_000_007L;
    Scanner scanner = new Scanner(System.in);
    String str = scanner.next();

    long[][] d = new long[str.length() + 1][4];
    d[0][0] = 1;
    for (int i = 1; i <= str.length(); i++) {
      char ch = str.charAt(i - 1);

      int n = ch == '?' ? 3 : 1;
      int a = 0, b = 0, c = 0;
      if (ch == 'A' || ch == '?') a = 1;
      if (ch == 'B' || ch == '?') b = 1;
      if (ch == 'C' || ch == '?') c = 1;
      d[i][0] = d[i - 1][0] * n % N;
      d[i][1] = d[i - 1][1] * n % N + a * d[i - 1][0];
      d[i][2] = d[i - 1][2] * n % N + b * d[i - 1][1];
      d[i][3] = d[i - 1][3] * n % N + c * d[i - 1][2];

      for (int j = 0; j < 4; j++) d[i][j] %= N;
    }

    System.out.println(d[str.length()][3]);
  }
}

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
	public static void main(String[] args) {
		try(Scanner sc = new Scanner(System.in)){
			int T=sc.nextInt();
			long a, b, c, d, e=0;
			Set<Long> set=new HashSet<>();

			for(int i=0; i<T; i++) {
				a=sc.nextLong();
				b=sc.nextLong();
				c=sc.nextLong();
				d=sc.nextLong();
				boolean tf=false;
				long count=0;
				if(b>a) {
					tf=true;
				}
				else if(b>d) {
					tf=false;
				}
				else if(c>=b) {
					tf=true;
				}
				else {
				while(true) {
					if(a<b) {
						tf=false;
						break;
					}
					if(count>0 && set.contains(a)) {
						tf=true;
						break;
					}

					set.add(a);
					e=a%b;
					if(e<=c) {
						a=e+d;
					}
					else if(e>c) {
						a=e;
					}
					count++;
				}
				}
				System.out.println(tf? "Yes":"No");
				set.clear();

			}
		}
	}
}

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

24
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


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

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

        FOR:
        for (int t = 0; t < T; t++) {
            long As = scanner.nextLong();
            long Bs = scanner.nextLong();
            long Cs = scanner.nextLong();
            long Ds = scanner.nextLong();
            List<Long> remains = new ArrayList<>();
//            int count = 0;
            if (Bs > Ds) {
                System.out.println("No");
                continue;
            }
            if (Cs >= Bs) {
                System.out.println("Yes");
                continue;
            }
            while (As >= Bs) {
//                System.out.println(As);
                long temp = (Bs * (As / Bs + Cs / Bs));
                int i = 0;
                while (temp > As) {
                    i++;
                    temp = (Bs * (As / Bs + Cs / Bs - i));
                }
                As -= (temp <= As ? temp : Bs);
//                System.out.println(As);
                if (As <= Cs) {
                    As += Ds;
                }

                if (remains.contains(As)) {
                    System.out.println("Yes");
                    continue FOR;
                } else {
                    remains.add(As);
                }

            }
            System.out.println("No");
        }
    }
}


public class Main {

  private static void solve() {
    int t = ni();
    for (int i = 0; i < t; i ++) {
      long a = nl();
      long b = nl();
      long c = nl();
      long d = nl();

      if (a < b || d < b) {
        System.out.println("No");
        continue;
      }
      //c本以下ならd本追加 d > b  b本消費
      //
      a %= b;
      if (a > c) {
        System.out.println("No");
        continue;
      }
      long gcd = gcd(b, d);
      if (b - gcd > c) {
        System.out.println("No");
        continue;
      }
      long x = c - a;
      a += x / c;
      System.out.println("Yes");
    }
  }

  public static long gcd(long a, long b) {
    if (a > b) {
        long tmp = a;
        a = b;
        b = tmp;
    }
    while (a != 0) {
        long c = a;
        a = b % c;
        b = c;
    }
    return b;
}

  public static void main(String[] args) {
    new Thread(null, new Runnable() {
      @Override
      public void run() {
        long start = System.currentTimeMillis();
        String debug = args.length > 0 ? args[0] : null;
        if (debug != null) {
          try {
            is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
        reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
        solve();
        out.flush();
        tr((System.currentTimeMillis() - start) + "ms");
      }
    }, "", 64000000).start();
  }

  private static java.io.InputStream is = System.in;
  private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
  private static java.util.StringTokenizer tokenizer = null;
  private static java.io.BufferedReader reader;

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

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

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

  private static int[] na(int n) {
    int[] a = new int[n];
    for (int i = 0; i < n; i++)
      a[i] = ni();
    return a;
  }

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

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

  private static int[][] ntable(int n, int m) {
    int[][] table = new int[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        table[i][j] = ni();
      }
    }
    return table;
  }

  private static int[][] nlist(int n, int m) {
    int[][] table = new int[m][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        table[j][i] = ni();
      }
    }
    return table;
  }

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

  private static void tr(Object... o) {
    if (is != System.in)
      System.out.println(java.util.Arrays.deepToString(o));
  }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.io.InputStream;

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

    static class TaskC {
        public void solve(int testNumber, FasterScanner in, PrintWriter out) {
            BigDecimal n = new BigDecimal(in.nextInt());
            BigDecimal m = new BigDecimal(in.nextInt() - 1);

            out.println(m.divide(n));
        }

    }

    static class FasterScanner {
        private InputStream in;
        private byte[] buffer;
        private int bufPointer;
        private int bufLength;

        public FasterScanner(InputStream in) {
            this.in = in;
            buffer = new byte[1024];
        }

        private boolean hasNextByte() {
            if (bufPointer < bufLength) return true;
            bufPointer = 0;
            try {
                bufLength = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (bufLength > 0);
        }

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

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

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

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

        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' || b > '9') throw new NumberFormatException();

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

    }
}

Score : 300 points

Problem Statement

Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d.
For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3.

There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusive).
Find the beauty of each of these n^m sequences, and print the average of those values.

Constraints

0 \leq d < n \leq 10^9

2 \leq m \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m d

Output

Print the average of the beauties of the sequences of length m where each element is an integer between 1 and n.
The output will be judged correct if the absolute or relative error is at most 10^{-6}.

Sample Input 1

2 3 1

Sample Output 1

1.0000000000

The beauty of (1,1,1) is 0.

The beauty of (1,1,2) is 1.

The beauty of (1,2,1) is 2.

The beauty of (1,2,2) is 1.

The beauty of (2,1,1) is 1.

The beauty of (2,1,2) is 2.

The beauty of (2,2,1) is 1.

The beauty of (2,2,2) is 0.

The answer is the average of these values: (0+1+2+1+1+2+1+0)/8=1.

Sample Input 2

1000000000 180707 0

Sample Output 2

0.0001807060


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

static long[] list=new long[87];

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

   String nyuA=sc.nextLine();

int N=Integer.parseInt(nyuA);

String[] data=sc.nextLine().split(" ");

int[] num=new int[data.length];

for(int i=0;i<data.length;i++){
num[i]=Integer.parseInt(data[i]);
}
Arrays.sort(num);

System.out.println(num[num.length-1]-num[0]);

}

}

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


import java.util.*;

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

        for(int i = 0;i<n;i++){
            a[i] = sc.nextInt();
        }
        Arrays.sort(a);
        int answer = a[n-1]-a[0];
        System.out.println(answer);
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        long minSum = 0;
        for (int i = 0; i < n; i++) {
            int num = sc.nextInt();
            nums[i] = num - (i + 1);
            minSum += Math.abs(nums[i]);
        }

        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            boolean stop = false;
            int minSumA = 0;
            for (int num : nums) {
                minSumA += Math.abs(num - i);
                if (minSumA >= minSum) {
                    stop = true;
                    break;
                }
            }

            if (!stop) {
                minSum = minSumA;
            } else {
                break;
            }
        }

        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            boolean stop = false;
            int minSumA = 0;
            for (int num : nums) {
                minSumA += Math.abs(num - i);
                if (minSumA >= minSum) {
                    stop = true;
                    break;
                }
            }

            if (!stop) {
                minSum = minSumA;
            } else {
                break;
            }
        }

        System.out.println(minSum);
    }
}

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] nums = new int[sc.nextInt()];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = sc.nextInt();
        }
        int b = -200000;
        int tmp = 0;
        int tmp2 = Integer.MAX_VALUE;
        int output = 0;
        for(int i=0;i<nums.length;i++){
            nums[i]-=i;
        }
        Arrays.sort(nums);
        int c=nums[(int)((nums.length+1)/2)-1];

        for(int i=0;i<nums.length;i++){
            if(nums[i]-c>=0){
                output+=nums[i]-c;
            }else{
               output-=nums[i]-c;
            }
        }
        System.out.println(output);

    }

}


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[] a = new int[n];

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

        int[] b = new int[n];
        for (int i = 0; i < n; i++) {
            b[i] = a[i] - (i+1);
        }

        Arrays.sort(b);
        int med = b[n/2];

        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.abs(b[i] - med);
        }

        System.out.println(ans);
    }
}