I tried to solve the past 10 questions that should be solved after registering with AtCoder in Java

Introduction

What to do next after registering with AtCoder-If you solve this much, you can fight enough! I tried to solve the problem introduced in the past 10 selected questions ~ with Java.

In the above article, the solution method in C ++ is written, and the article that I tried to solve in other languages is introduced, so here I will try to use Java-specific methods as much as possible. However, Java is a language based on C ++, so a similar implementation is possible in C ++ ...

Question 1: ABC 086 A --Product

It is a question of the evenness of the product of two integers. It's a basic problem.

In Java, when receiving input, System.in is passed to Scanner and used. Also, use several methods depending on the type of data received.

--For words, next () --nextInt () for integers --nextLine () for a string (1 line)

This time we are dealing with integers, so we are using nextInt ().

As a side note, when dealing with integers, ʻInteger.parseInt (sc.next ())is faster thannextInt (), or Scanner` is slow in the first place, so people who use their own Scanner method. There seems to be. If you are interested, please try google.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        if ((a * b) % 2 == 0)
            System.out.println("Even");
        else
            System.out.println("Odd");
    }
}

Question 2: ABC 081 A --Placing Marbles

It is a problem to count "1" in the given three-digit number.

It is a problem dealing with numbers, but since it is easy to solve if it is treated as a character string, next () is used. It's a string consisting only of "0" and "1", so if you look at the length of the rest of the string without the "0", that's the answer. Let's replace "0" with "" with replaceAll ().

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        s = s.replaceAll("0", "");
        System.out.println(s.length());
    }
}

Question 3: ABC 081 B --Shift Only

The problem is how many times you can divide several integers at the same time when you divide them by 2 until one of them is not divisible.

The fact that a number is divisible by 2 is the same as the fact that the 1s place is 0 when expressed in binary. In other words, how many times a number is divisible by 2 can be found by examining the number of 0s that continues from the bottom. You can do this for all numbers or values to find the answer for the smallest number that can be divided by two. You can find the number of 0s following the bottom with ʻInteger.numberOfTrailingZeros ()`.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int bit = 0;
        for (int i=0; i<N; i++) {
            bit |= sc.nextInt();
        }
        System.out.println(Integer.numberOfTrailingZeros(bit));
    }
}

Question 4: ABC 087 B --Coins

It is a question of how many ways to pay a certain amount using 500-yen coins, 100-yen coins, and 50-yen coins.

Determine the number of 500-yen coins and 100-yen coins with a for statement, and calculate the number of 50-yen coins by the difference from X. Since the condition of the problem states that X is a multiple of 50, there is no need to consider the case where the number of 50-yen coins becomes a decimal.

import java.util.*;

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

        int res = 0;
        for (int a=0; a<=A; a++) {
            for (int b=0; b<=B; b++) {
                int c = (X - a * 500 - b * 100) / 50;
                if (c >= 0 && c <= C)
                    res++;
            }
        }

        System.out.println(res);
    }
}

Question 5: ABC 083 B --Some Sums

For numbers less than or equal to N, the problem is to find the total number of numbers A or more and B or less.

Here, we will obediently examine the sum of each digit for each value between 1 and N. It is the while statement that calculates the sum of each digit. n% 10 adds the least significant value to digSum, and n / = 10 discards the least significant digit. Decimal numbers are more cumbersome to handle than binary numbers, and I hate them ...

import java.util.*;

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

        int sum = 0;
        for (int i=1; i<=N; i++) {
            int n = i;
            int digSum = 0;
            while (n > 0) {
                digSum += n % 10;
                n /= 10;
            }
            if (digSum >= A && digSum <= B)
                sum += i;
        }
        System.out.println(sum);
    }
}

Question 6: ABC 088 B --Card Game for Two

Consider a game in which you have several cards with numbers on them, and two people take them alternately and compete for the total. At this time, the problem is to find out how many numbers the first player can take than the second player.

In order to get the cards that maximize each other's points, we will take the card with the largest number of cards in play. In other words, the cards are sorted in descending order, and the cards are taken alternately from the beginning.

Use ʻArrays.sort ()to sort the arrays. Also, this time we want to sort in descending order, so passComparator.reverseOrder ()as the second argument. By the way, if you want to sortList, use Collections.sort () . Java uses List` more often than arrays, so you may be more likely to use it.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        Integer a[] = new Integer[N];
        for (int i=0; i<N; i++) {
            a[i] = sc.nextInt();
        }
        Arrays.sort(a, Comparator.reverseOrder());

        int Alice = 0;
        int Bob   = 0;
        for (int i=0; i<N; i+=2) {
            Alice += a[i];
        }
        for (int i=1; i<N; i+=2) {
            Bob += a[i];
        }
        System.out.println(Alice - Bob);
    }
}

Question 7: ABC 085 B --Kagami Mochi

When there are several rice cakes of various sizes, it is a question of how many stages of kagami mochi can be made using only rice cakes of different sizes.

Set is useful for problems dealing with non-duplicate numbers. Set can store any number of objects like List, but duplicates will be ignored. You can easily find the answer by adding the size of all rice cakes to Set and finally counting the number of data that Set has.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        Set<Integer> num = new HashSet<>();
        for (int i=0; i<N; i++) {
            int di = sc.nextInt();
            num.add(di);
        }
        System.out.println(num.size());
    }
}

Question 8: ABC 085 C --Otoshidama

There are 10000 yen bills, 5000 yen bills, and 1000 yen bills, and the problem is to find a combination that makes the total of N and Y yen.

It's a similar problem to Question 4. The solution method is similar, such as using a double for statement.

import java.util.*;

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

        for (int a=0; a<=N; a++) {
            for (int b=0; b<=N-a; b++) {
                int c = N - a - b;
                int total = a * 10000 + b * 5000 + c * 1000;
                if (total == Y) {
                    System.out.println(a + " " + b + " " + c);
                    return;
                }
            }
        }

        System.out.println("-1 -1 -1");
    }
}

Question 9: ABC 049 C --Daydream

It is a problem to judge whether a certain character string can be made by concatenating a combination of "dream", "dreamer", "erase", and "eraser".

If you apply the character string from the beginning, the beginning of "dreamerase" will match "dreamer", or the beginning of "dreamererase" will match "dream", so check from the back. From behind, such mistakes do not occur.

Use ʻendsWith ()to find out if one string matches the bottom of another. Of course, there is alsostartsWith ()`, which checks if one string matches the beginning of another.

import java.util.*;

class Main {
    static String[] strs = {
        "dream",
        "dreamer",
        "erase",
        "eraser"
    };

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

        while (true) {
            boolean endsWithStr = false;
            for (String str: strs) {
                if (S.endsWith(str)) {
                    endsWithStr = true;
                    S = S.substring(0, S.length() - str.length());
                    break;
                }
            }
            if (!endsWithStr) {
                System.out.println("NO");
                break;
            }
            if (S.length() <= 0) {
                System.out.println("YES");
                break;
            }
        }
    }
}

I tried to write it, but in fact, I can't pass it with AtCoder in this answer. It's MLE ... Apparently the cause is too much string generation. I made some improvements and made the code without ʻendsWith ()` and it passed, but it's not interesting to put it, so I'll put another solution.


Simply replace each string and delete it. In this method, devise the order of the character strings to be deleted so that accidental deletion does not occur. Delete dreamer before dream, eraser before erase, erase and eraser before dreamer.

[Addition] With this method, you will mistakenly think that a string like "dreameraseer" can be composed of erase and dreamer. When replacing, replace it with an unused character without an empty string, and finally delete that character to get the correct result. Thank you to @ CuriousFairy315 for pointing this out!

import java.util.*;

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

        S = S.replaceAll("eraser",  "-");
        S = S.replaceAll("erase",   "-");
        S = S.replaceAll("dreamer", "-");
        S = S.replaceAll("dream",   "-");
        S = S.replaceAll("-", "");
        if (S.length() == 0)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

Question 10: ABC 086 C -Traveling

The problem is to start at coordinates (0, 0) and determine if we can be at (xi, yi) at time ti.

If it is possible to reach the target coordinates by the time, you can adjust the time by wandering around, but if you arrive at the target coordinates before the odd time of the time, it will be at the exact time. Note that you cannot be at the desired coordinates.

import java.util.*;

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

in conclusion

I'm a chick who has been in the competition for about a month, so there are likely to be many better solutions. (Please let us know in the comments!)

Java isn't that slow at the moment, but it's still slower than C or C ++ and consumes more memory. In fact, if I wrote the former implementation in C ++, I could pass the 9th question normally. It would be nice if there were relaxation of time and memory restrictions for each language like AOJ, but with AtCoder, all languages are equal.

I feel that using C ++ is the best way to compete with AtCoder. (Of course, it's fun to solve in other languages!) I myself am currently studying C ++ for a competitive professional. If you are a competitive professional other than C ++, let's start C ++ at this time! (What is the recommendation of C ++ in Java articles ...)

Recommended Posts

I tried to solve the past 10 questions that should be solved after registering with AtCoder in Java
I tried to solve 10 selected past questions that should be solved after registering with AtCoder with Java, Stream API
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I tried to implement the Euclidean algorithm in Java
I tried to interact with Java
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to summarize the words that I often see in docker-compose.yml
[Java] I want to perform distinct with the key in the object
I tried the new era in Java
[Introduction to Java] I tried to summarize the knowledge that I think is essential
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I tried to make Basic authentication with Java
I tried to organize the session in Rails
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
I tried to implement deep learning in Java
I tried to output multiplication table in Java
I tried to make a program that searches for the target class from the process that is overloaded with Java
I didn't know that inner classes could be defined in the [Java] interface
I tried to create Alexa skill in Java
I tried to break a block with java (1)
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
I want to change the path after new registration after logging in with multiple devises.
The story that the variable initialization method called in the Java constructor should not be overridden
I tried to organize the cases used in programming
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
[Java] I tried to solve Paiza's B rank problem
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to implement Stalin sort with Java Collector
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
I didn't understand the topological sort, so I looked it up and implemented it in BFS, and then tried to solve the AtCoder problem.
I tried to create an Amazon echo skill that teaches scraped information in Java using the Alexa Skills Kit (ASK)
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
After posting an article with Rails Simple Calendar, I want to reflect it in the calendar.
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
I tried a puzzle that can only be solved by the bottom 10% of bad engineers
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[Java] ArrayList → Should I specify the size in array conversion?
I want to set the conditions to be displayed in collection_check_boxes
I tried to increase the processing speed with spiritual engineering
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to convert a string to a LocalDate type in Java
I tried using Dapr in Java to facilitate microservice development
I tried to make a client of RESAS-API in Java
Be sure to compare the result of Java compareTo with 0
I tried using the CameraX library with Android Java Fragment
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool
I tried to be able to pass multiple objects with Ractor
I want to simplify the conditional if-else statement in Java
I tried to express the result of before and after of Date class with a number line
[Java] I want to check that the elements in the list are null or empty [Collection Utils]
After learning Progate, I tried to make an SNS application using Rails in the local environment