//package javaapplication1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import static java.lang.reflect.Array.set;
import java.math.BigInteger;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import static jdk.nashorn.internal.objects.Global.Infinity;
import static jdk.nashorn.internal.objects.NativeMath.round;
import sun.awt.HKSCS;

/*
   PARTIAL AUTHOR GEORGE
   MAINLY GEEKSFORGEEKS ALL RIGHTS RESERVED.
*/
public class Main {
    static boolean isSubSequence(String str1, String str2, int m, int n)
    {

        if (m == 0)
            return true;
        if (n == 0)
            return false;

        if (str1.charAt(m-1) == str2.charAt(n-1))
            return isSubSequence(str1, str2, m-1, n-1);

        return isSubSequence(str1, str2, m, n-1);
    }

        public static void main(String[] args) throws IOException{
        BufferedReader BR=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter PW=new PrintWriter(new PrintStream(System.out));
        In IN=new In(BR);
        Out OUT=new Out(PW);
        Scanner SC=new Scanner(System.in);
        //DataStructure DS=new DataStructure();
        Functions F=new Functions();
        //QuickSort QS=new QuickSort();
        //BinarySearch BS=new BinarySearch();
        //FIB fubbonanci=new FIB(93);
        //Map<Character,List<Integer>>Pos=new HashMap<>();
        //Set<Integer>ans=new HashSet<>();
        //StringPermutationGenerator SPG=new StringPermutationGenerator();
        long n,m;
        n=IN.nextLong();
        m=IN.nextLong();
            for (long i = n; i <=Math.pow(10, 18); i*=n) {
                if(i%m!=0){System.out.println(i);System.exit(0);}
            }
            for (long i = m; i <=Math.pow(10, 18); i*=m) {
                if(i%n!=0){System.out.println(i);System.exit(0);}
            }
            System.out.println(-1);
   }

    protected static class In {
        private BufferedReader reader;
        private StringTokenizer tokenizer = new StringTokenizer("");
        public In(BufferedReader reader) {
            this.reader = reader;
        }

        public String next() throws IOException {
            while (!tokenizer.hasMoreTokens())
                tokenizer = new StringTokenizer(reader.readLine());
            return tokenizer.nextToken();
        }

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

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

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

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

        public int[] nextIntArray1(int n) throws IOException {
            int[] a = new int[n + 1];
            for (int i = 1; i <= n; i++)
                a[i] = nextInt();
            return a;
        }

        public int[] nextIntArraySorted(int n) throws IOException {
            int[] a = nextIntArray(n);
            Random r = new Random();
            for (int i = 0; i < n; i++) {
                int j = i + r.nextInt(n - i);
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
            Arrays.sort(a);
            return a;
        }

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

        public long[] nextLongArray1(int n) throws IOException {
            long[] a = new long[n + 1];
            for (int i = 1; i <= n; i++)
                a[i] = nextLong();
            return a;
        }

        public long[] nextLongArraySorted(int n) throws IOException {
            long[] a = nextLongArray(n);
            Random r = new Random();
            for (int i = 0; i < n; i++) {
                int j = i + r.nextInt(n - i);
                long t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
            Arrays.sort(a);
            return a;
        }
    }
    protected static class Out {
        private PrintWriter writer;
        private static boolean local = System
                .getProperty("ONLINE_JUDGE") == null;

        public Out(PrintWriter writer) {
            this.writer = writer;
        }

        public void print(char c) {
            writer.print(c);
        }

        public void print(int a) {
            writer.print(a);
        }

        public void println(Object a) {
            writer.println(a);
        }

        public void println(Object[] os) {
            for (int i = 0; i < os.length; i++) {
                writer.print(os[i]);
                writer.print(' ');
            }
            writer.println();
        }

        public void println(int[] a) {
            for (int i = 0; i < a.length; i++) {
                writer.print(a[i]);
                writer.print(' ');
            }
            writer.println();
        }

        public void println(long[] a) {
            for (int i = 0; i < a.length; i++) {
                writer.print(a[i]);
                writer.print(' ');
            }
            writer.println();
        }

        public static void db(Object... objects) {
            if (local)
                System.out.println(Arrays.deepToString(objects));
        }
    }
    public static class QuickSort{
    protected static int [] intArray;
    protected static long [] longArray;
    protected static double [] DoubleArray;
    protected static char [] charArray;
    protected static int Size;
        public QuickSort() {
        }

    protected static int partition(int arr[],int low,int high)
    {
      int pivot=arr[high];
      int i=low-1;
      int temp=0;
        for (int j = low; j < high; ++j) {
            if(arr[j]<=pivot)
            {
                 ++i;
                 temp = arr[i];
                 arr[i] = arr[j];
                 arr[j] = temp;
            }
        }
         temp = arr[i+1];
         arr[i+1] = arr[high];
         arr[high] = temp;
         return i+1;

    }
    protected static int partition(long arr[],int low,int high)
    {
      long pivot=arr[high];
      int i=low-1;
      long temp=0;
        for (int j = low; j < high; ++j) {
            if(arr[j]<=pivot)
            {
                 ++i;
                 temp = arr[i];
                 arr[i] = arr[j];
                 arr[j] = temp;
            }
        }
         temp = arr[i+1];
         arr[i+1] = arr[high];
         arr[high] = temp;
         return i+1;

    }
    protected static int partition(double arr[],int low,int high)
    {
      double pivot=arr[high];
      int i=low-1;
      double temp=0;
        for (int j = low; j < high; ++j) {
            if(arr[j]<=pivot)
            {
                 ++i;
                 temp = arr[i];
                 arr[i] = arr[j];
                 arr[j] = temp;
            }
        }
         temp = arr[i+1];
         arr[i+1] = arr[high];
         arr[high] = temp;
         return i+1;

    }
    protected static int partition(char arr[],int low,int high)
    {
      char pivot=arr[high];
      int i=low-1;
      char temp=0;
        for (int j = low; j < high; ++j) {
            if(arr[j]<=pivot)
            {
                 ++i;
                 temp = arr[i];
                 arr[i] = arr[j];
                 arr[j] = temp;
            }
        }
         temp = arr[i+1];
         arr[i+1] = arr[high];
         arr[high] = temp;
         return i+1;

    }
    protected static void sort(int arr[],int low, int high)
    {
          if(low < high)
          {
              int pi=partition(arr, low, high);
              sort(arr, low, pi-1);
              sort(arr, pi+1, high);

          }

    }
   protected static void sort(long arr[],int low, int high)
    {
          if(low < high)
          {
              int pi=partition(arr, low, high);
              sort(arr, low, pi-1);
              sort(arr, pi+1, high);

          }
    }

    protected static void sort(double arr[],int low, int high)
    {
          if(low < high)
          {
              int pi=partition(arr, low, high);
              sort(arr, low, pi-1);
              sort(arr, pi+1, high);

          }
    }
    protected static void sort(char arr[],int low, int high)
    {
          if(low < high)
          {
              int pi=partition(arr, low, high);
              sort(arr, low, pi-1);
              sort(arr, pi+1, high);

          }
    }
    protected  static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    protected  static void printArray(char arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    protected  static void printArray(double arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
     protected  static void printArray(long arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
  }
    public static class Functions{

        public Functions() {
        }
        protected static boolean [] sieveOfEratosthenesPrimes(int limit){
        boolean prime[] = new boolean[limit+1];
        for(int i=0;i<limit;i++)
            prime[i] = true;
        for(int p = 2; p*p <=limit; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*2; i <= limit; i += p)
                    prime[i] = false;
            }
        }
         return prime;
    }
    protected static boolean checkAnagram(String str1, String str2) {
        int i=0;
        for (char c : str1.toCharArray()) {
        i = str2.indexOf(c, i) + 1;
        if (i <= 0) { return false; }
    }
    return true;
    }
    protected static boolean contains(final int[] arr, final int key) {
    return Arrays.stream(arr).anyMatch(i -> i == key);
    }
    public static boolean contains(final long[] arr, final long key) {
    return Arrays.stream(arr).anyMatch(i -> i == key);
    }
    public static boolean contains(final double[] arr, final double key) {
    return Arrays.stream(arr).anyMatch(i -> i == key);
    }
    protected static long NCR(long N, long R){
    if(N < R)
        return 0;
    if(R == 0 || R == N)
        return 1;
    return NCR(N-1,R-1)+NCR(N-1,R);
    }
    protected static long NCR(int N, int R){
    if(N < R)
        return 0;
    if(R == 0 || R == N)
        return 1;
    return NCR(N-1,R-1)+NCR(N-1,R);
    }
    protected static String changeCharInPosition(int position, char ch, String str){
    char[] charArray = str.toCharArray();
    charArray[position] = ch;
    return new String(charArray);
    }
    protected static boolean isPrime(long n) {
    if(n < 2) return false;
    if(n == 2 || n == 3) return true;
    if(n%2 == 0 || n%3 == 0) return false;
    long sqrtN = (long)Math.sqrt(n)+1;
    for(long i = 6L; i <= sqrtN; i += 6) {
        if(n%(i-1) == 0 || n%(i+1) == 0) return false;
    }
    return true;
    }
    protected static long Gcd(long p, long q) {
        if (q == 0) return p;
        else return Gcd(q, p % q);
     }
    protected static boolean isPrime(int n) {
    if(n < 2) return false;
    if(n == 2 || n == 3) return true;
    if(n%2 == 0 || n%3 == 0) return false;
    int sqrtN = (int)Math.sqrt(n)+1;
    for(long i = 6L; i <= sqrtN; i += 6) {
        if(n%(i-1) == 0 || n%(i+1) == 0) return false;
    }
    return true;
    }
 }
  public static class BinarySearch{
        private static int middle;
        private static int L;
        private static int R;
        public BinarySearch() {

        }
        protected static int Search(int [] arr,int element){
         R=arr.length-1;
         L=0;
         return BS(arr, L, R, element);
        }
        protected static int Search(long [] arr,long element){
         R=arr.length-1;
         L=0;
         return BS(arr, L, R, element);
        }
        protected static int Search(char [] arr,char element){
         R=arr.length-1;
         L=0;
         return BS(arr, L, R, element);
        }
        protected static int Search(double [] arr,double element){
         R=arr.length-1;
         L=0;
         return BS(arr, L, R, element);
        }
         protected static int BS(int [] arr,int L,int R,int element){
          if(R>=L)
          {
            middle=L+(R-L)/2;
            if(arr[middle]==element)
            {
                return middle;
            }
            else if(arr[middle]>element)
            {
                return BS(arr, L,middle-1, element);
            }
            else
            {
                return BS(arr, middle+1, R, element);
            }
          }
          else
            {
              return -1;
            }
          }
         protected static int BS(long [] arr,int L,int R,long element){
          if(R>=L)
          {
            middle=L+(R-L)/2;
            if(arr[middle]==element)
            {
                return middle;
            }
            else if(arr[middle]>element)
            {
                return BS(arr, L,middle-1, element);
            }
            else
            {
                return BS(arr, middle+1, R, element);
            }
          }
          else
            {
              return -1;
            }
          }
         protected static int BS(char [] arr,int L,int R,char element){
          if(R>=L)
          {
            middle=L+(R-L)/2;
            if(arr[middle]==element)
            {
                return middle;
            }
            else if(arr[middle]>element)
            {
                return BS(arr, L,middle-1, element);
            }
            else
            {
                return BS(arr, middle+1, R, element);
            }
          }
          else
            {
              return -1;
            }
          }
         protected static int BS(double [] arr,int L,int R,double element){
          if(R>=L)
          {
            middle=L+(R-L)/2;
            if(arr[middle]==element)
            {
                return middle;
            }
            else if(arr[middle]>element)
            {
                return BS(arr, L,middle-1, element);
            }
            else
            {
                return BS(arr, middle+1, R, element);
            }
          }
          else
            {
              return -1;
            }
          }
    }
    public static class DataStructure{

        public DataStructure() {
        }

     static void stack_push(Stack<Integer> stack)
    {
        for(int i = 0; i < 5; i++)
        {
            stack.push(i);
        }
    }

    // Popping element from the top of the stack
    static void stack_pop(Stack<Integer> stack)
    {
        System.out.println("Pop :");

        for(int i = 0; i < 5; i++)
        {
            Integer y = (Integer) stack.pop();
            System.out.println(y);
        }
    }

    // Displaying element on the top of the stack
    static void stack_peek(Stack<Integer> stack)
    {
        Integer element = (Integer) stack.peek();
        System.out.println("Element on stack top : " + element);
    }

    // Searching element in the stack
    static void stack_search(Stack<Integer> stack, int element)
    {
        Integer pos = (Integer) stack.search(element);

        if(pos == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element is found at position " + pos);
    }

    }
   public static class FIB {

    protected static int MAX = 1000;
    protected static long f[];
    protected static int size=0;
    // Returns n'th fibonacci number using
    // table f[]

    public FIB(int n)
    {
        f=new long[MAX];
        this.size=n;
        fib();
    }

        protected static void fib() {
            f[0]=0;f[1]=1;
            for (int i = 2; i < size; i++) {
                //if(f[i-1]+f[i-2]>Long.MAX_VALUE){f[i]=0;continue;}
                f[i]=f[i-1]+f[i-2];
            }
        }
        protected static void printSeries(){
            for (int i = 0; i <size; i++) {
                System.out.print(f[i]+" ");
            }

        }
    }
    public static class Graph{

    }
   public static class StringPermutationGenerator {
    // Generate all permutations of a string in Java
    private Set<String> generatePermutations(String input) {

        input = input.toLowerCase();
        Set<String> result = new HashSet<>();
        permutations("", input, result);
        return result;

    }
     private void permutations(String prefix, String letters, Set<String> result) {

        if (letters.length() == 0) {

            result.add(prefix);

        } else {

            for (int i = 0; i < letters.length(); i++) {

                String letter = letters.substring(i, i + 1);

                String otherLetters = letters.substring(0, i) + letters.substring(i + 1);

                permutations(prefix + letter, otherLetters, result);

            }

        }

    }

    }
}
/*
Some References for doing things
-Removing all Leading zeros in a string
s.replaceFirst("^0+(?!$)", "");
-Creating comprator
public static class CustomComparator implements Comparator<c> {
    @Override
    public int compare(c o1, c o2) {
        return o1.score.compareTo(o2.score);
    }
}
-how to write switch case
   switch(x)
   {
    case 1:
    return l;
    ...
    default:
    return m;
   }
-Convert numbers of and to different bases
  Integer.toString(Integer.parseInt(number, base1), base2);
-Split over white spaces:
  myString.split("\\s+");
-how to know if 4 points will form a square or a rectangle:
    public static class point{
            int a,b;
            public point(int a, int b) {
                this.a = a;
                this.b = b;
                }

            @Override
            public String toString() {
                return "point{" + "a=" + a + ", b=" + b + '}';
                }
            }
            public static int distSq(point p, point q)
            {
            return (p.a - q.a)*(p.a - q.a) +
                    (p.b - q.b)*(p.b - q.b);
             }
         public static boolean isSquare(point p1, point p2, point p3, point p4)
    {
        int d2 = distSq(p1, p2);  // from p1 to p2
        int d3 = distSq(p1, p3);  // from p1 to p3
        int d4 = distSq(p1, p4);  // from p1 to p4

        // If lengths if (p1, p2) and (p1, p3) are same, then
        // following conditions must met to form a square.
        // 1) Square of length of (p1, p4) is same as twice
        //    the square of (p1, p2)
        // 2) p4 is at same distance from p2 and p3
        if (d2 == d3 && 2*d2 == d4)
        {
            int d = distSq(p2, p4);
            return (d == distSq(p3, p4) && d == d2);
        }

        // The below two cases are similar to above case
        if (d3 == d4 && 2*d3 == d2)
        {
            int d = distSq(p2, p3);
            return (d == distSq(p2, p4) && d == d3);
        }
        if (d2 == d4 && 2*d2 == d3)
        {
            int d = distSq(p2, p3);
            return (d == distSq(p3, p4) && d == d2);
        }

        return false;
    }
      public static boolean isRectangle(point p1,point p2,point p3,point p4)
    {
      double cx,cy;
      double dd1,dd2,dd3,dd4;
      double x1,y1,x2,y2,x3,y3,x4,y4;
      x1=p1.a;y1=p1.b;x2=p2.a;y2=p2.b;x3=p3.a;y3=p3.b;x4=p4.a;y4=p4.b;
      cx=(x1+x2+x3+x4)/4;
      cy=(y1+y2+y3+y4)/4;

      dd1=(cx-x1)*(cx-x1)+(cy-y1)*(cy-y1);
      dd2=(cx-x2)*(cx-x2)+(cy-y2)*(cy-y2);
      dd3=(cx-x3)*(cx-x3)+(cy-y3)*(cy-y3);
      dd4=(cx-x4)*(cx-x4)+(cy-y4)*(cy-y4);
      return dd1==dd2 && dd1==dd3 && dd1==dd4;
    }
*/

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


import java.util.stream.*;
import java.util.*;

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

    public static void main(String[]$) {
        int n = scanner.nextInt();
        int i = 0, j = 0;
        int[] a = IntStream.range(0, n).map(k -> scanner.nextInt()).toArray();
        for (int k = 0; k < n; k++) {
            a[k] -= scanner.nextInt();
            if (a[k] < 0) {
                i -= a[k];
            } else {
                j += a[k];
            }
        }
        System.out.println(i > 2 * j ? "Yes" : "No");
    }
}

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

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No

Submitted source-code file size, in bytes.

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

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


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

public class Main {
    static final class UnionFindTree {
        private final int[] parent;
        private final long[] weight;
        public UnionFindTree(int n) {
            if (n < 1) {
                throw new IllegalArgumentException();
            }
            parent = new int[n];
            Arrays.setAll(parent, i -> i);

            weight = new long[n];
        }
        public int root(int x) {
            if (parent[x] == x) {
                return x;
            }
            int r = root(parent[x]);
            weight[x] += weight[parent[x]];
            return parent[x] = r;
        }
        public boolean same(int x, int y) {
            return root(x) == root(y);
        }
        public boolean unite(int x, int y) {
            return unite(x, y, 0);
        }
        public boolean unite(int x, int y, long w) {
            int xr = root(x);
            int yr = root(y);
            if (xr == yr) {
                return false;
            }
            weight[yr] = w + weight(x) - weight(y);
            parent[yr] = xr;
            return true;
        }
        public long weight(int x) {
            root(x);
            return weight[x];
        }
        public long diff(int x, int y) {
            if (same(x, y)) {
                return weight(y) - weight(x);
            }
            throw new IllegalArgumentException();
        }
    }
    static void solve(MyScanner in, MyWriter out) {
        int n = in.nextInt();
        int m = in.nextInt();
        int[][] lrd = in.nextVerticalIntArrays(3, m);
        int[] l = lrd[0];
        int[] r = lrd[1];
        int[] d = lrd[2];
        UnionFindTree t = new UnionFindTree(n);
        for (int i = 0; i < m; i++) {
            int left = l[i] - 1;
            int right = r[i] - 1;
            if (t.same(left, right)) {
                if (t.diff(left, right) != d[i]) {
                    out.println("No");
                    return;
                }
            } else {
                t.unite(left, right, d[i]);
            }
        }
        out.println("Yes");
    }

    public static void main(String[] args) {
        MyWriter w = new MyWriter(System.out);
        solve(new MyScanner(System.in), w);
        w.flush();
    }

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

Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

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

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

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

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes


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

    for(int i=0; i<N; i++){
      int postT = sc.nextInt();
      int postX = sc.nextInt();
      int postY = sc.nextInt();

      int dt = postT - preT;
      int dist = Math.abs(postX - preX) + Math.abs(postY - preY);
      if ((dt < dist) || ((dist - dt) % 2 != 0)) {
        System.out.println("No");
        return;
      }

      preT = postT;
      preX = postX;
      preY = postY;
    }

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

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<Integer> t = new ArrayList<>();
        List<Integer> x = new ArrayList<>();
        List<Integer> y = new ArrayList<>();
        t.add(0);
        x.add(0);
        y.add(0);
        for(int i = 0;i < n;i++){
            t.add(sc.nextInt());
            x.add(sc.nextInt());
            y.add(sc.nextInt());
        }
        for(int i = 1;i < n;i++){
            int dt = t.get(i) - t.get(i-1);
            int dist = Math.abs(x.get(i)-x.get(i-1)) + Math.abs(y.get(i)-y.get(i-1));
            if(dist <= dt && ((dist % 2) == (dt % 2))){
                System.out.println("Yes");
                return;
            }
        }
        System.out.println("No");
    }
}


import java.util.Scanner;

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

	Scanner sc = new Scanner(System.in);

	void run(){
		int N = sc.nextInt();

		int prevT = 0;
		int prevX = 0;
		int prevY = 0;
		boolean mutFlag = true;
		for (int i = 0; i < N ; i++){
			int t = sc.nextInt();
			int x = sc.nextInt();
			int y = sc.nextInt();

			mutFlag = check(t,x,y,prevT,prevX,prevY);
			if(!mutFlag){
				break;
			}
			prevT = t;
			prevX = x;
			prevY = y;
		}
		System.out.println(mutFlag ?"Yes" :"No");

	}

	boolean check(int t1,int x1,int y1, int t0,int x0,int y0){
		int time = t1 - t0;

		int distance = Math.abs(x1 - x0) + Math.abs(y1 - y0);
		if((distance + time) % 2 == 1){
			return false;
		}
		return distance <= time;
	}
}


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

        if((b-a)%2 == 0){
            System.out.println("Alice");
        }else{
            System.out.println("Borys");
        }

    }
}

Score : 300 points

Problem Statement

A game is played on a strip consisting of N cells consecutively numbered from 1 to N.

Alice has her token on cell A. Borys has his token on a different cell B.

Players take turns, Alice moves first.
The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or on the right, cell X+1.
Note that it's disallowed to move the token outside the strip or to the cell with the other player's token.
In one turn, the token of the moving player must be shifted exactly once.

The player who can't make a move loses, and the other player wins.

Both players want to win. Who wins if they play optimally?

Constraints

2 \leq N \leq 100

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print Alice if Alice wins, Borys if Borys wins, and Draw if nobody wins.

Sample Input 1

5 2 4

Sample Output 1

Alice

Alice can move her token to cell 3.
After that, Borys will be unable to move his token to cell 3, so he will have to move his token to cell 5.
Then, Alice moves her token to cell 4. Borys can't make a move and loses.

Sample Input 2

2 1 2

Sample Output 2

Borys

Alice can't make the very first move and loses.

Sample Input 3

58 23 42

Sample Output 3

Borys


import java.util.Scanner;

public class Main {

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

        S = "2018" + S.substring(4,10);
        System.out.println(S);
    }

}

Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


import java.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Integer time = sc.nextInt();
		System.out.println((24 - time) + 24);
	}
}

Score : 100 points

Problem Statement

How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?

Constraints

1≤M≤23

M is an integer.

Input

Input is given from Standard Input in the following format:

M

Output

If we have x hours until New Year at M o'clock on 30th, December, print x.

Sample Input 1

21

Sample Output 1

27

We have 27 hours until New Year at 21 o'clock on 30th, December.

Sample Input 2

12

Sample Output 2

36


/*
長さの制約を忘れていた
どもるがんの法則、間が&&ではなく||だった
*/

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();
    String blank = sc.nextLine();
    String s = sc.nextLine();
    int i = 0;
    boolean flag = true;

    if(s.charAt(a) != '-'){flag = false;}
    for(char c : s.toCharArray()){
      i++;
      if(i == a){continue;}
      if(!('0' <= c) || !(c <= '9')){flag = false; break;}
      //i++;
      //continueされたときにiiを進めれてないのが問題
    }
    if(s.length() != a+b+1){flag = false;}

    if(flag){System.out.println("Yes");}
    else{System.out.println("No");}

  }
}

/*
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String blank = sc.nextLine();
String s = sc.nextLine();
System.out.println();
System.exit(0)
*/

Score : 200 points

Problem Statement

The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen -, and the other characters are digits from 0 through 9.

You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

Print Yes if S follows the postal code format in AtCoder Kingdom; print No otherwise.

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

The (A+1)-th character of S is -, and the other characters are digits from 0 through 9, so it follows the format.

Sample Input 2

1 1
---

Sample Output 2

No

S contains unnecessary -s other than the (A+1)-th character, so it does not follow the format.

Sample Input 3

1 2
7444

Sample Output 3

No


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int q = sc.nextInt();
    ArrayList<Integer> list = sosu(100000);
    int[] s = new int[100001];
    for(int i = 1;i<=100000;i++){
      if(list.contains(i)&&list.contains((i+1)/2))s[i]=s[i-1]+1;
      else s[i]=s[i-1];
    }
    for(int i = 0;i < q;i++){
      int l = sc.nextInt();
      int r = sc.nextInt();
      System.out.println(s[r]-s[l-1]);
    }
  }
  public static ArrayList<Integer> sosu(int n){
    boolean[] a = new boolean[n+1];
    Arrays.fill(a,true);
    ArrayList<Integer> list = new ArrayList<>();
    for(int i = 4;i <= n;i+=2)a[i]=false;
    for(int i = 3;i <= Math.sqrt(n);i+=2){
      if(a[i]){
        for(int j = i*2;j <= n;j+=i)a[j]=false;
      }
    }
    for(int i = 2;i <= n;i++)if(a[i])list.add(i);
    return list;
  }
}

Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th query.

Sample Input 1

1
3 7

Sample Output 1

2

3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.

5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.

7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2


import java.util.Scanner;

public class Main {

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int A = sc.nextInt();
		int B = sc.nextInt();
		int C = sc.nextInt();
		int D = sc.nextInt();
		int left = A + B;
		int right = C + D;
		if (left > right)
			System.out.println("Left");
		else if (left == right)
			System.out.println("Balanced");
		else {
			System.out.println("Right");
		}
		sc.close();
	}
}

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        Long X = Long.parseLong(s);
        String line = sc.next();
        Long Y = Long.parseLong(line);
        Long sum = X * 2;
        int count = 2;

        while(true){
            sum = sum * 2;
            if(sum > Y){
                System.out.println(count);
                System.exit(0);
            }
            count++;
            if(X == count){
                System.out.println(count);
                System.exit(0);
            }
        }
    }
}

Score : 300 points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:

A consists of integers between X and Y (inclusive).

For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.

Find the maximum possible length of the sequence.

Constraints

1 \leq X \leq Y \leq 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


import java.util.Scanner;

class Main{
	public static void main(String[]$){
		Scanner s=new Scanner(System.in);
		String c=s.next();
		int max=c.length();
		for(int i=1;i<c.length();++i)
			if(c.charAt(i)!=c.charAt(i-1))
				max=Math.min(max,Math.max(i,c.length()-i));
		System.out.println(max);
	}
}

Score : 500 points

Problem Statement

You are given a string S consisting of 0 and 1.
Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0 by repeating the following operation some number of times.

Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfied). For each integer i such that l\leq i\leq r, do the following: if S_i is 0, replace it with 1; if S_i is 1, replace it with 0.

Constraints

1\leq |S|\leq 10^5

S_i(1\leq i\leq N) is either 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum integer K such that we can turn all the characters of S into 0 by repeating the operation some number of times.

Sample Input 1

010

Sample Output 1

2

We can turn all the characters of S into 0 by the following operations:

Perform the operation on the segment S[1,3] with length 3. S is now 101.

Perform the operation on the segment S[1,2] with length 2. S is now 011.

Perform the operation on the segment S[2,3] with length 2. S is now 000.

Sample Input 2

100000000

Sample Output 2

8

Sample Input 3

00001111

Sample Output 3

4


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

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

    double average = Math.ceil( (a+b)/2 );
    System.out.println(average);
  }
}

Score : 100 points

Problem Statement

You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2.

Sample Input 2

7 4

Sample Output 2

6

The average of 7 and 4 is 5.5, and it will be rounded up to the nearest integer, 6.

Sample Input 3

5 5

Sample Output 3

5


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

class Main {

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

        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String[] numbers = br.readLine().split(" ");

            double average = (Integer.parseInt(numbers[0]) + Integer.parseInt(numbers[1])) / 2;
            int roundUpAverage = (int) Math.ceil(average);

            System.out.println(roundUpAverage);
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
            System.exit(0);
        } catch (final Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}


import java.util.Scanner;

public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    Integer a, b, c, d;
    a = sc.nextInt();
    b = sc.nextInt();
    c = (a+b)/2;
    d = (a+b)%2;
    System.out.println(c);
    if(d == 0){
      System.out.println(c);
    }else{
      System.out.println(c + 1);
    }

  }
}


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

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String[] s = in.nextLine().split("");
		String[] t = in.nextLine().split("");

		Arrays.parallelSort(s);
		Arrays.parallelSort(t, Collections.reverseOrder());

		String newS = String.join("", s);
		String newT = String.join("", t);

		System.out.println(newS.compareTo(newT) < 0 ? "Yes" : "No");

		/*if (newS.equals(newT)) {
			System.out.println("No");
		} else {
			System.out.println(newS.compareTo(newT) <= 0 ? "Yes" : "No");
		}
		*/
	}

}

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


import java.util.*;

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

		List<Integer> xmv = new ArrayList<Integer>();
		List<Integer> ymv = new ArrayList<Integer>();

		int cnt = 0;
		boolean goX = true;
		for(int i=0;i<s.length()+1;i++) {
			if(i!=s.length()&&s.charAt(i)=='F')cnt++;
			else {
				if(goX) {
					xmv.add(cnt);
					goX = false;
				}else {
					ymv.add(cnt);
					goX = true;
				}
				cnt = 0;
			}
		}

		int xmax = 0;
		for(int i=0;i<xmv.size();i++)xmax+=xmv.get(i);

		//xについて
		boolean dp[][] = new boolean[8080][16050];
		dp[0][xmv.get(0)+8000]=true;
		for(int i=1;i<xmv.size();i++) {
			int dist = xmv.get(i);
			for(int j=-xmax;j<=xmax;j++) {
				dp[i][j+8000] = dp[i-1][j-dist+8000]||dp[i-1][j+dist+8000];
			}
		}

		//yについてコピー
		int ymax = 0;
		for(int i=0;i<ymv.size();i++)ymax+=ymv.get(i);

		//xについて
		boolean dpy[][] = new boolean[8080][16050];
		if(ymv.size()==0)ymv.add(0);
		dpy[0][ymv.get(0)+8000]=true;
		for(int i=1;i<ymv.size();i++) {
			int dist = ymv.get(i);
			for(int j=-ymax;j<=ymax;j++) {
				dpy[i][j+8000] = dpy[i-1][j-dist+8000]||dpy[i-1][j+dist+8000];
			}
		}

		String ans = "No";
		if(dp[xmv.size()-1][x+8000]&&dpy[ymv.size()-1][y+8000]) ans = "Yes";
		System.out.println(ans);

	}
}

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


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

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 n=0;n<N;n++) a[n]=sc.nextInt();
        Arrays.sort(a);

        int remove=0;
        int sameElement=1;
        for(int n=1;n<N;n++){
        	if(a[n]==a[n-1]){
        		sameElement++;
        	}else{
        		if(sameElement>=a[n-1]) remove += (sameElement-a[n-1]);
        		else remove += sameElement;
        		sameElement=1;
        	}
        }
        if(sameElement>=a[N-1]) remove += (sameElement-a[N-1]);
        else remove += sameElement;

        System.out.println(remove);

    }
}

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

5


import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int count = Integer.parseInt(sc.nextLine());
		int[] num = new int[count];
		int[] max = new int[count];
		int maxOperate = 0;
		System.out.println("count"+ count);
		for(int i = 0 ; i < count ;i++) {
			num[i] = sc.nextInt();
			System.out.println("i:"+i+ ",num" +num[i]);
			max[i] = 0;
			while((num[i]%2)==0) {
				num[i] = num[i]/2;
				max[i] += 1;
			}
			if(i == 0) {
				maxOperate = max[i];
			}else if(maxOperate > max[i]) {
				maxOperate = max[i];
			}
		}
		System.out.println(maxOperate);
	}

}

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

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 operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


import java.util.*;

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

        boolean judge = true;
        int count = 0;
        //条件に合っているときに繰り返す
        while(judge){
            //奇数があるなら止める
            for(int j=0; j<n; j++){
                if(a[j] % 2 == 1){
                    judge = false;
                }
            }
            //割れるなら2で割る
            if(judge){
                //2で割る
                for(int k=0; k<n; k++){
                    a[k] /= 2;
                }
                //割った回数カウントする
                count++;
            }
        }

        System.out.println(count);
    }
}


import java.util.*;
import java.io.*;
public class Main
{
	public static void main(String[] args) throws IOException
	{
		Reader in=new Reader();
		int n=in.nextInt(),k=in.nextInt();
		int a[]=new int[n];
		for(int i=0; i<n; i++)
			a[i]=in.nextInt();
		Arrays.sort(a);
		int[] occs=new int[200001];
		int ct=1,te=1000000000;
		for(int i=0; i<n; i++)
		{
			if(te==a[i])
			{
				ct++;
			}
			else if(te!=1000000000)
			{
			//	System.out.println(ct+" "+a[i]);
				occs[ct]++;
				ct=1;
				te=a[i];
			}
			else
				te=a[i];
		}
		occs[ct]++;
		int sum=0,ans=0;
		for(int i=200000; i>0; i--)
		{
			if(sum<k)
			{
				sum+=occs[i];
				if(sum>k)
					ans+=(sum-k)*i;
	//			System.out.println(ans+" "+i);
			}
			else
			{
				ans+=occs[i]*i;
	//			System.out.println(ans+" "+i);

			}
		}
		System.out.println(ans);
	}
	static StringBuilder ans=new StringBuilder();
	static class Reader
	    {
	        final private int BUFFER_SIZE = 1 << 16;
	        private DataInputStream din;
	        private byte[] buffer;
	        private int bufferPointer, bytesRead;
	        StringTokenizer st;

	        public Reader()
	        {
	            din = new DataInputStream(System.in);
	            buffer = new byte[BUFFER_SIZE];
	            bufferPointer = bytesRead = 0;
	        }

	        public Reader(String file_name) throws IOException
	        {
	            din = new DataInputStream(new FileInputStream(file_name));
	            buffer = new byte[BUFFER_SIZE];
	            bufferPointer = bytesRead = 0;
	        }

	        public String next() throws IOException
	        {
	        	while(st==null||!st.hasMoreElements())
	        	{
	        		try
	        		{
	        			st=new StringTokenizer(readLine());
	        		}
	        		catch(IOException e)
	        		{
	        			e.printStackTrace();
	        		}
	        	}
	        	return
	        			st.nextToken();
	        }
	        public String readLine() throws IOException
	        {
	            byte[] buf = new byte[64]; // line length
	            int cnt = 0, c;
	            while ((c = read()) != -1)
	            {
	                if (c == '\n')
	                    break;
	                buf[cnt++] = (byte) c;
	            }
	            return new String(buf, 0, cnt);
	        }

	        public int nextInt() throws IOException
	        {
	            int ret = 0;
	            byte c = read();
	            while (c <= ' ')
	                c = read();
	            boolean neg = (c == '-');
	            if (neg)
	                c = read();
	            do
	            {
	                ret = ret * 10 + c - '0';
	            }  while ((c = read()) >= '0' && c <= '9');

	            if (neg)
	                return -ret;
	            return ret;
	        }

	        public long nextLong() throws IOException
	        {
	            long ret = 0;
	            byte c = read();
	            while (c <= ' ')
	                c = read();
	            boolean neg = (c == '-');
	            if (neg)
	                c = read();
	            do {
	                ret = ret * 10 + c - '0';
	            }
	            while ((c = read()) >= '0' && c <= '9');
	            if (neg)
	                return -ret;
	            return ret;
	        }

	        public double nextDouble() throws IOException
	        {
	            double ret = 0, div = 1;
	            byte c = read();
	            while (c <= ' ')
	                c = read();
	            boolean neg = (c == '-');
	            if (neg)
	                c = read();

	            do {
	                ret = ret * 10 + c - '0';
	            }
	            while ((c = read()) >= '0' && c <= '9');

	            if (c == '.')
	            {
	                while ((c = read()) >= '0' && c <= '9')
	                {
	                    ret += (c - '0') / (div *= 10);
	                }
	            }

	            if (neg)
	                return -ret;
	            return ret;
	        }

	        private void fillBuffer() throws IOException
	        {
	            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
	            if (bytesRead == -1)
	                buffer[0] = -1;
	        }

	        private byte read() throws IOException
	        {
	            if (bufferPointer == bytesRead)
	                fillBuffer();
	            return buffer[bufferPointer++];
	        }

	        public void close() throws IOException
	        {
	            if (din == null)
	                return;
	            din.close();
	        }
	    }
}

Score : 300 points

Problem Statement

Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.

He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

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

Sample Output 3

3


Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


import java.util.*;
public class Main {
	public static void main(String[] args) {
		A();
	}

	public static void A() {
		Scanner sc = new Scanner(System.in);
		Integer n = sc.nextInt();
		sc.close();
		String num = n.toString();
		if(num.charAt(1) != num.charAt(2)) {
			System.out.println("No");
			return;
		}
		char mid = num.charAt(1);
		if(mid == num.charAt(0) || mid == num.charAt(3)) {
			System.out.println("Yes");
		}
		else System.out.println("No");
	}

}

Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


import java.util.*;
class Main
{
    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        char c0 = s.charAt(0), c1 = s.charAt(1),
             c2 = s.charAt(2), c3 = s.charAt(3);
        String ans = "No";
        if((c0 == c1 || c2 == c3) && (c1 == c2)) ans = "Yes";
        System.out.print(ans);
    }
}


import java.util.*;

public class Main {

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

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

		int commit = 1<<M;

		System.out.println(commit * (M*1900 + (N-M)*100));

		sc.close();
	}
}

Score : 300 points

Problem Statement

Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is YES or NO.

When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.

Then, he rewrote the code to correctly solve each of those M cases with 1/2 probability in 1900 milliseconds, and correctly solve each of the other N-M cases without fail in 100 milliseconds.

Now, he goes through the following process:

Submit the code.

Wait until the code finishes execution on all the cases.

If the code fails to correctly solve some of the M cases, submit it again.

Repeat until the code correctly solve all the cases in one submission.

Let the expected value of the total execution time of the code be X milliseconds. Print X (as an integer).

Constraints

All input values are integers.

1 \leq N \leq 100

1 \leq M \leq {\rm min}(N, 5)

Input

Input is given from Standard Input in the following format:

N M

Output

Print X, the expected value of the total execution time of the code, as an integer. It can be proved that, under the constraints in this problem, X is an integer not exceeding 10^9.

Sample Input 1

1 1

Sample Output 1

3800

In this input, there is only one case. Takahashi will repeatedly submit the code that correctly solves this case with 1/2 probability in 1900 milliseconds.

The code will succeed in one attempt with 1/2 probability, in two attempts with 1/4 probability, and in three attempts with 1/8 probability, and so on.

Thus, the answer is 1900 \times 1/2 + (2 \times 1900) \times 1/4 + (3 \times 1900) \times 1/8 + ... = 3800.

Sample Input 2

10 2

Sample Output 2

18400

The code will take 1900 milliseconds in each of the 2 cases, and 100 milliseconds in each of the 10-2=8 cases. The probability of the code correctly solving all the cases is 1/2 \times 1/2 = 1/4.

Sample Input 3

100 5

Sample Output 3

608000


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

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

    static class Rotation {
        public void solve(int testNumber, FastReader in, PrintWriter out) {
            String first = in.next();
            String second = new StringBuilder(in.next()).reverse().toString();
            if (first.equals(second)) {
                out.println("YES");
            } else {
                out.println("NO");
            }
        }

    }

    static class FastReader {
        BufferedReader reader;
        StringTokenizer st;

        public FastReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            st = null;
        }

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

    }
}

Score : 100 points

Problem Statement

You are given a grid with 2 rows and 3 columns of squares.
The color of the square at the i-th row and j-th column is represented by the character C_{ij}.

Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise.

Constraints

C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

C_{11}C_{12}C_{13}
C_{21}C_{22}C_{23}

Output

Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise.

Sample Input 1

pot
top

Sample Output 1

YES

This grid remains the same when rotated 180 degrees.

Sample Input 2

tab
bet

Sample Output 2

NO

This grid does not remain the same when rotated 180 degrees.

Sample Input 3

eye
eel

Sample Output 3

NO


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class Main {

	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskX solver = new TaskX();
		solver.solve(1, in, out);
		out.close();
	}

	static class TaskX {
		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int n = in.nextInt();
			int[] a = in.nextIntArray(n);
			Arrays.sort(a);
			int[] b = in.nextIntArray(n);
			int[] c = in.nextIntArray(n);
			Arrays.sort(c);

			long count = 0L;
			for (int i = 0; i < n; i++) {
				long ubc = ArrayUtils.lowerBinarySearch(a, b[i]);
				long obc = n - (ArrayUtils.upperBinarySearch(c, b[i]));
				count += (ubc * obc);
			}
			out.println(count);

		}

	}

	static class ArrayUtils {
		public static Map<Integer, Integer> getCountMap(int[] array) {
			Map<Integer, Integer> map = new TreeMap<>();
			for (int x : array)
				map.merge(x, 1, Integer::sum);
			return map;
		}
		/**
		 * 指定された要素以上の値が現れる最初の位置のイテレータを取得する
		 * */
		public static int lowerBinarySearch(int[] a, int obj) {
			int l = 0,r = a.length - 1;
			while (r - l >= 0) {
				int c = (l + r) / 2;
				if (obj <= a[c]) {
					r = c - 1;
				} else {
					l = c + 1;
				}
			}
			return l;
		}

		/**
		 * 指定された要素より大きい値が現れる最初の位置のイテレータを取得する
		 * */
		public static int upperBinarySearch(int[] a, int obj) {
			int l = 0,r = a.length - 1;
			while (r - l >= 0) {
				int c = (l + r) / 2;
				if (a[c] <= obj) {
					l = c + 1;
				} else {
					r = c - 1;
				}
			}
			return l;
		}

	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

		public String nextString() {
			while (!tok.hasMoreTokens()) {
				try {
					tok = new StringTokenizer(in.readLine(), " ");
				} catch (IOException e) {
					throw new InputMismatchException();
				}
			}
			return tok.nextToken();
		}

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

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

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

		public InputReader(InputStream inputStream) {
			in = new BufferedReader(new InputStreamReader(inputStream));
			tok = new StringTokenizer("");
		}

	}

}

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


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

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

	static class TaskD {
		public void solve(int testNumber, FastScanner in, PrintWriter out) {
			int k = in.nextInt();
			int ans = Integer.MAX_VALUE;
			for (int i = 1; i <= (int) 3e7; i++) {
				long x = (long) i * k;
				int cur = 0;
				while (x > 0) {
					cur += x % 10;
					x /= 10;
				}
				ans = Math.min(ans, cur);
			}
			out.println(ans);
		}

	}

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

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

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

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

	}
}

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


import java.util.*;

public class Main{

    private void print(int[] arrayMid){
        StringBuilder Mid = new StringBuilder();
        for(int i = 0; i < arrayMid.length; i++){
            Mid.append(arrayMid[i] + " ");
        }
        System.out.print(Mid);
    }

    private void Even(int K, int N){
        int[] arrayMid = new int[N];
        arrayMid[0] = K/2;
        for(int i = 1; i < N; i ++){
            arrayMid[i] = K;
        }
        print(arrayMid);
    }

    private void Odd(int K, int N){
        int[] arrayMid = new int[N];
        for(int i = 0; i < N; i ++){
            arrayMid[i] = (K + 1) / 2;
        }
        for(int i = 0; i < N / 2; i ++){
            if(arrayMid[arrayMid.length - 1] == 1) arrayMid = Arrays.copyOf(arrayMid, arrayMid.length - 1);
            else arrayMid[arrayMid.length - 1] --;
        }
        print(arrayMid);
    }

    private void Judge(int K, int N){
        if(K % 2 == 0) Even(K, N);
        else Odd(K, N);
    }

    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        int[] in = new int[2];
        for(int i = 0; i < 2; i++){
            in[i] = input.nextInt();
        }
        Main myEncyclopedia = new Main();
        myEncyclopedia.Judge(in[0], in[1]);
        input.close();

    }
}

Score : 800 points

Problem Statement

In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.

Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.

Constraints

1 \leq N,K \leq 3 × 10^5

N and K are integers.

Input

Input is given from Standard Input in the following format:

K N

Output

Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.

Sample Input 1

3 2

Sample Output 1

2 1

There are 12 sequences listed in FEIS: (1),(1,1),(1,2),(1,3),(2),(2,1),(2,2),(2,3),(3),(3,1),(3,2),(3,3).
The (12/2 = 6)-th lexicographically smallest one among them is (2,1).

Sample Input 2

2 4

Sample Output 2

1 2 2 2

Sample Input 3

5 14

Sample Output 3

3 3 3 3 3 3 3 3 3 3 3 3 2 2


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 = 1;
        System.out.println(2 * k - n);
    }
}

Score : 100 points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be a.

Suppose that the performance of the user in the contest is b.

Then, the new rating of the user will be the avarage of a and b.

For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000.

Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest.

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

If his performance in the contest is 2032, his rating will be the average of 2002 and 2032, which is equal to the desired rating, 2017.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between 0 and 4500, the performance of a user can be below 0.


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

public class Main {

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

		String S = in.readLine();

		if(S.indexOf("AC") > 0) {
			System.out.println("Yes");
		}else{
			System.out.println("No");
		}
	}

}

Score : 100 points

Problem Statement

Snuke built an online judge to hold a programming contest.

When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring.
(The judge can return any two-character substring of S.)

Determine whether the judge can return the string AC as the verdict to a program.

Constraints

2 \leq |S| \leq 5

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If the judge can return the string AC as a verdict to a program, print Yes; if it cannot, print No.

Sample Input 1

BACD

Sample Output 1

Yes

The string AC appears in BACD as a contiguous substring (the second and third characters).

Sample Input 2

ABCD

Sample Output 2

No

Although the string ABCD contains both A and C (the first and third characters), the string AC does not appear in ABCD as a contiguous substring.

Sample Input 3

CABD

Sample Output 3

No

Sample Input 4

ACACA

Sample Output 4

Yes

Sample Input 5

XX

Sample Output 5

No


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] d = new int[n];
    for(int i = 0;i < n;i++)d[i]=sc.nextInt();
    int m = sc.nextInt();
    int[] t = new int[m];
    for(int i = 0;i < m;i++)t[i]=sc.nextInt();
    Arrays.sort(d);
    Arrays.sort(t);
    int cnt = 1;
    Map<Integer,Integer> map = new HashMap<>();
    for(int i = 0;i < n-1;i++){
      if(d[i]==d[i+1])cnt++;
      else{
        map.put(d[i],cnt);
        cnt=1;
      }
    }
    map.put(d[n-1],cnt);
    boolean ans = true;
    cnt=1;
    for(int i = 0;i < m-1;i++){
      if(t[i]==t[i+1])cnt++;
      else{
        if(map.get(t[i])==null)ans=false;
        else if(map.get(t[i])<cnt)ans=false;
        cnt=1;
      }
    }
    if(map.get(t[m-1])==null)ans=false;
    else if(map.get(t[m-1])<cnt)ans=false;
    System.out.println((ans)?"YES":"NO");
  }
}

Score : 200 points

Problem Statement

Rng is preparing a problem set for a qualification round of CODEFESTIVAL.

He has N candidates of problems. The difficulty of the i-th candidate is D_i.

There must be M problems in the problem set, and the difficulty of the i-th problem must be T_i. Here, one candidate of a problem cannot be used as multiple problems.

Determine whether Rng can complete the problem set without creating new candidates of problems.

Constraints

1 \leq N \leq 200,000

1 \leq D_i \leq 10^9

1 \leq M \leq 200,000

1 \leq T_i \leq 10^9

All numbers in the input are integers.

Partial Score

100 points will be awarded for passing the test set satisfying N \leq 100 and M \leq 100.

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N
M
T_1 T_2 ... T_M

Output

Print YES if Rng can complete the problem set without creating new candidates of problems; print NO if he cannot.

Sample Input 1

5
3 1 4 1 5
3
5 4 3

Sample Output 1

YES

Sample Input 2

7
100 200 500 700 1200 1600 2000
6
100 200 500 700 1600 1600

Sample Output 2

NO

Not enough 1600s.

Sample Input 3

1
800
5
100 100 100 100 100

Sample Output 3

NO

Sample Input 4

15
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
9
5 4 3 2 1 2 3 4 5

Sample Output 4

YES


import java.util.*;

class Main{
  public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    String s=sc.next();
    int max=0;
    for(int i=0;i<6;i++){
      max+=s.charAt(i)-'0';
    }
    System.out.println(max);
  }
}

Score : 100 points

Problem Statement

Snuke prepared 6 problems for a upcoming programming contest.
For each of those problems, Rng judged whether it can be used in the contest or not.

You are given a string S of length 6.
If the i-th character of s is 1, it means that the i-th problem prepared by Snuke is accepted to be used; 0 means that the problem is not accepted.

How many problems prepared by Snuke are accepted to be used in the contest?

Constraints

The length of S is 6.

S consists of 0 and 1.

Inputs

Input is given from Standard Input in the following format:

S

Outputs

Print the number of problems prepared by Snuke that are accepted to be used in the contest.

Sample Input 1

111100

Sample Output 1

4

The first, second, third and fourth problems are accepted, for a total of four.

Sample Input 2

001001

Sample Output 2

2

Sample Input 3

000000

Sample Output 3

0


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 littledream1502@gmail.com
 */
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);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int N = in.nextInt();
            int h, n, w;
            for (int i = 1; i < 3501; i++) {
                for (int j = 1; j < 3501; j++) {
                    long l = N * i * j;
                    long r = 4 * i * j - N * i - N * j;
                    if (r > 0 && l % r == 0) {
                        long result = l / r;
                        out.println(i + " " + j + " " + r);
                        return;
                    }
                }
            }
        }

    }

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

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

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

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

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

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

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

        }

    }

    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 print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

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

    }
}

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


// 作者：杨成瑞先生
import java.io.*;
import java.util.*;

public class Main {

	static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner() {
            try {
                br = new BufferedReader(new InputStreamReader(System.in));
                st = new StringTokenizer(br.readLine());
            } catch (Exception e){e.printStackTrace();}
        }

        public String next() {
            if (st.hasMoreTokens()) return st.nextToken();
            try {st = new StringTokenizer(br.readLine());}
            catch (Exception e) {e.printStackTrace();}
            return st.nextToken();
        }

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

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

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

        public String nextLine() {
            String line = "";
            if(st.hasMoreTokens()) line = st.nextToken();
            else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
            while(st.hasMoreTokens()) line += " "+st.nextToken();
            return line;
        }
    }

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

        pw.println(sc.nextLine().substring(0, 5).contains("YAKI") ? "YES" : "NO");

        pw.close();
	}

}

Score : 100 points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with YAKI.

Constraints

1 \leq |S| \leq 10

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No