Implement a circular expression binary search in Python. There is a comparison with a simple full search.

For example, this [problem] of AtCoder (https://atcoder.jp/contests/abc146/tasks/abc146_c?lang=ja) (C of abc146)

When I try to solve it with a linear search, the search range is $ 1 ≤ A ≤ 10 ^ {9} $, so the calculation does not finish in time. (* TLE is about $ 10 ^ {8} $ to $ 10 ^ {9} $.)

Let's implement it as a trial.

A,B,X = map(int,input().split())

max_int = 0
for i in range(1,10**9+1):
    if (A * i) + ( B * (len(str(i))) ) <= X:
        max_int = i
    else:
        break

print(max_int)

It is an implementation that honestly investigates from scratch, but when you submit this, as expected, most of them will be TLE. Looking at this algorithm, it checks whether the condition is satisfied by increasing it by 1 in order from 1.

This is the same as searching for a sorted array of $ 1,2,3,4,5,6 ,,,, 10 ^ {9} $. Speaking of algorithms that can be used when sorted like this ,. Yes, it's a binary search.

Let's implement it in the same way as described in the algorithm textbook.

A,B,X = map(int,input().split())

#Define a range of integers you want to search
left = 1
right = 10 ** 9

#Conditions to be met
def validate(arg):
    if (A * arg) + ( B * (len(str(arg))) ) <= X:
        return True

#Binary search to find the maximum integer that satisfies the condition
max_int = 0
while left <= right:
    mid = (left+right) // 2
    if validate(mid):
        max_int = mid
        left = mid + 1
    else:
        right = mid -1

print(max_int)

In a normal binary search, the While statement is exited when a value that satisfies the condition is found, but this problem is to find the maximum integer that satisfies the condition, so continue as it is. However, the point is to update max_int only if the conditions are met. Using mid in this code for the answer is buggy.

This is not a problem, but as pointed out in the formula, it is easy to get a bug at the final boundary judgment if you are not careful about mid + 1 and mid -1. Also, the condition judgment of While is a point where it is easy to make a mistake as to whether it is <or <=.

So, if you rewrite it with reference to the Meguru formula, it will be like this.

※※ Meguru-shiki Honke here


A,B,X = map(int,input().split())

#Define a range of integers you want to search
left = 0
right = 10 ** 9 + 1

#Conditions to be met
def validate(arg):
    if (A * arg) + ( B * (len(str(arg))) ) <= X:
        return True

#Binary search to find the maximum integer that satisfies the condition
max_int = 0
while abs(right - left) > 1:
    mid = (left+right) // 2
    if validate(mid):
        max_int = mid
        left = mid
    else:
        right = mid

print(max_int)

In the case of the Meguru formula, the point is to increase it by one from the upper and lower limits of the range you want to search. In the case of this code, left = 0 right = 10 ** 9 + 1.

It doesn't look like a big change, but you don't have to worry about the disappearance of +1 -1 and> = or>.

When the difference between abs (right --left) becomes 1, the process ends.

Recommended Posts

Implement a circular expression binary search in Python. There is a comparison with a simple full search.
Write a binary search in Python
Solve the subset sum problem with a full search in Python
Implement a simple application with Python full scratch without using a web framework.
Binary search in Python
Binary search with python
Binary search with Python3
Binary search in Python (binary search)
Make a simple Slackbot with interactive button in python
What is God? Make a simple chatbot with python
Try to implement permutation full search that often appears in competition pros with python
Binary search in Python / C ++
Algorithm in Python (binary search)
Full bit search with Python
Determine if a string is a time with a python regular expression
[python] Reverse with slices! !! (There is also a commentary on slices!)
[Python] What is a with statement?
Is there a special in scipy? ??
Create a binary file in Python
I want to do a full text search with elasticsearch + python
There is no switch in python
Write a depth-first search in Python
Implementing a simple algorithm in Python 2
Run a simple algorithm in Python
What to do if there is a decimal in python json .dumps
Creating a simple PowerPoint file with Python
Use print in a Python2 lambda expression
A simple HTTP client implemented in Python
Try working with binary data in Python
Algorithm in Python (ABC 146 C Binary Search
Try drawing a simple animation in Python
Create a simple GUI app in Python
Search the maze with the python A * algorithm
Playing card class in Python (with comparison)
Hash in Perl is a dictionary in Python
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
I made a simple blackjack with Python
python Binary search It is surprisingly easy to implement bisect.bisect_left and bisect.bisect_right from 0
A confusing story with two ways to implement XGBoost in Python + overall notes
Set up a simple HTTPS server in Python 3
Launch a simple password-protected search service in 5 minutes
[Python] Get the files in a folder with Python
Create a virtual environment with conda in Python
Start a simple Python web server with Docker
A story stuck with handling Python binary data
[Python] Make a simple maze game with Pyxel
A simple Pub / Sub program note in Python
Create a simple momentum investment model in Python
Work in a virtual environment with Python virtualenv.
Create a new page in confluence with Python
Set up a simple SMTP server in Python
Implement similar face search in half a day
A simple to-do list created with Python + Django
Implement "All You Need Is Kill" in Python
Use Search Tweets: Full Archive / Sandbox in Python
Hello World is a simple web server that follows WSGI (Web Server Gateway Interface) in Python.
Check if the string is a number in python
How to convert / restore a string with [] in python
I want to easily implement a timeout in python
Write a super simple molecular dynamics program in python