When it becomes TLE with Python, you can get AC with PyPy, and conversely, when you become TLE with PyPy, you can get AC with Python.
In Problem A of AtCoder Typical Contest 001, there is a problem of depth-first search.
So I wrote the following code.
test.py
import sys
sys.setrecursionlimit(500*500)
def dfs(px,py):
if px < 0 or py < 0 or px > w-1 or py > h-1:
return False
if c[py][px] == '#':
return False
if c[py][px] == 'g':
return True
c[py][px] = '#'
if dfs(px-1,py):
return True
if dfs(px,py-1):
return True
if dfs(px+1,py):
return True
if dfs(px,py+1):
return True
return False
h,w = map(int,input().split())
c = []
for i in range(h):
s = input()
x = s.find('s')
if x != -1:
start = [x,i]
c.append(list(s))
sx = int(start[0])
sy = int(start[1])
if dfs(sx,sy):
print('Yes')
else:
print('No')
I think that it is a fairly straightforward way of writing as a depth-first search.
As a result of submitting this, it became as follows.
I got AC in Python3, but it has become TLE in PyPy3.
It seems that ** PyPy is incompatible with recursive functions **, which is the cause.
You can take AC either way by using the stack quietly without using recursive functions.
AtCoder Beginner Contest 153 E Problem was a problem that could be solved using dynamic programming.
So I wrote the following code.
test.py
H,N= map(int,input().split())
a = []
b = []
for i in range(N):
a_dash,b_dash = map(int,input().split())
a.append(a_dash)
b.append(b_dash)
#dp[i+1][j] =Become a monster with physical strength j with magic up to the i-th
#Minimum amount of magical power that can be won
INF = 10**9
dp = [[INF for _ in range(H+1)] for _ in range(N+1)]
#Monsters with 0 health have died from the beginning
for i in range(N+1):
dp[i][0] = 0
for i in range(N):
for j in range(H+1):
if a[i] > j:
dp[i+1][j] = min(dp[i][j],b[i])
else:
dp[i+1][j] = min(dp[i][j],dp[i+1][j-a[i]]+ b[i])
print(dp[N][H])
Without any special ingenuity, the code is simply similar to the unlimited number knapsack problem.
When I submitted this, the following results were returned.
This time it became AC with PyPy and TLE with Python3.
Of course, there is also a way to solve it in Python.
** I think the correct answer is to write a beautiful answer that allows you to get AC regardless of which one you use.
However, I'm a beginner in competition pros, so I'll use PyPy for the time being, and use Python when using recursive functions **.
By the way, PyPy seems to have the disadvantage that some libraries written in C language cannot be used.
Since I am a beginner in competition professionals, please point out any deficiencies in the above contents.
Recommended Posts