はじめに
競プロにおいてpypyはCPythonに比べて速い処理系です。多くの場合はpypyで事足ります。
ただPythonはスクリプト言語のため、C++などのコンパイル言語に比べると圧倒的に遅く、同じ処理がTLEになることがあります。
そんな時に便利なのがcodonです。
ここ数年で出てきた処理系で、一度コンパイルしてから実行することにより、処理が格段に速い特徴があります。
しかし、型に厳密であったりオーバーフローの危険があるなど、普段のPythonで意識していない部分を要求されます。
負の無限大丸めなど、普段書いている書き方が書けない場合も多々あります。
この記事では、pypyでの書き方を最大限尊重したうえで、提出時のみcodonで出せるようなマクロを紹介します。
それぞれのサイトに合わせたマクロをコード上部にコピペするだけで、pypyのコードがcodonで動くようになる運用を想定しています。
なおここで紹介するコードは以下のnavel_tosさんの記事のコードを集約、一部改変したものです。
https://qiita.com/navel_tos/items/9195de7041cf2c8b535b
AtCoder(Codon 0.19.3)、ShareOJ(Codon 0.20)共通マクロ
import math, sys
# https://qiita.com/navel_tos/items/9195de7041cf2c8b535b
#mapの返り値をlist(map)で固定
import internal.static as _internal_static
def map(f, *args) -> list:
if _internal_static.len(args) == 0:
compile_error("map() expects at least one iterator")
elif _internal_static.len(args) == 1:
return [f(a) for a in args[0]]
else:
return [f(*a) for a in zip(*args)]
@extend
class int:
#int同士の除算結果をPythonの負の無限大丸めに合わせる
@pure
@llvm
def _floordiv_int_int(self: int, other: int) -> int:
%0 = sdiv i64 %self, %other
ret i64 %0
@overload
def __floordiv__(self, other: int):
d = self._floordiv_int_int(other)
m = self - d * other
if m and ((other ^ m) < 0):
d -= 1
return d
@pure
@llvm
def _mod_int_int(self: int, other: int) -> int:
%0 = srem i64 %self, %other
ret i64 %0
@overload
def __mod__(self, other: int) -> int:
m = self._mod_int_int(other)
if m and ((other ^ m) < 0):
m += other
return m
#int.bit_length, int.bit_countに対応
@pure
@llvm
def _ctlz(self) -> int:
declare i64 @llvm.ctlz.i64(i64, i1)
%0 = call i64 @llvm.ctlz.i64(i64 %self, i1 false)
ret i64 %0
def bit_length(self) -> int:
return 64 - abs(self)._ctlz() if self else 0
@pure
@llvm
def _ctpop(a: int) -> int:
declare i64 @llvm.ctpop.i64(i64 %a)
%0 = call i64 @llvm.ctpop.i64(i64 %a)
ret i64 %0
def bit_count(self) -> int:
return abs(self)._ctpop()
#int hash値をSplitMix64で変更する
#Reference: https://prng.di.unimi.it/splitmix64.c
def __hash__(self) -> int:
z: UInt[64] = UInt[64](self) + UInt[64](0x9e3779b97f4a7c15)
z = (z ^ (z >> UInt[64](30))) * UInt[64](0xbf58476d1ce4e5b9)
z = (z ^ (z >> UInt[64](27))) * UInt[64](0x94d049bb133111eb)
return int(z ^ (z >> UInt[64](31)))
#Int[N](N <= 128)同士の除算結果をPythonの負の無限大丸めに合わせる
@extend
class Int:
def __floordiv__(self, other: Int[N]) -> Int[N]:
if N > 128:
compile_error("division is not supported on Int[N] when N > 128")
d = self._floordiv(other)
m = self - d * other
if m and ((other ^ m) < Int[N](0)):
d -= Int[N](1)
return d
def __mod__(self, other: Int[N]) -> Int[N]:
if N > 128:
compile_error("modulus is not supported on Int[N] when N > 128")
m = self._mod(other)
if m and ((other ^ m) < Int[N](0)):
m += other
return m
#floatの出力桁数を15桁に増やす
@extend
class float:
def __str__(self): return f'{self:.15f}'
#巨大mod時のオーバーフローを回避 pow(base, -1, mod)に対応
def _extended_pow():
_builtin_pow = pow
def _codon_pow(base, exp):
return _builtin_pow(base, exp)
@overload
def _codon_pow(base: int, exp: int, mod: int) -> int:
'''
codon用に pow(base, exp, mod) を拡張した関数です。
1. (abs(mod) - 1) ** 2 >= 1 << 63 の場合に発生していたオーバーフローを回避しました。
2. pow(base: int, exp: 負整数, mod: int) による逆元計算に対応しました。
返り値の符号は mod の符号に一致します。
いずれかの引数に INF_MIN := -1 << 63 を渡した場合の動作は未定義です。
'''
if mod == 0:
raise ValueError('pow() 3rd argument cannot be 0')
if mod == 1 or mod == -1:
return 0
if exp < 0: #拡張ユークリッドの互除法
a, b, x, y = base, mod, 1, 0
while b:
q = a // b
a, b, x, y = b, a - q * b, y, x - q * y
if a != 1 and a != -1:
raise ValueError('base is not invertible for the given modulus')
b128, m128 = Int[128](x), Int[128](mod)
if a == -1:
b128 = - b128
exp = - exp
else:
b128, m128 = Int[128](base), Int[128](mod)
v128 = Int[128](1)
while exp:
if exp & 1 == 1:
v128 = v128 * b128 % m128
b128 = b128 * b128 % m128
exp >>= 1
v = int(v128)
return v + mod if v != 0 and (0 < v) != (0 < mod) else v
return _codon_pow
def isqrt(n: int) -> int:
if n <= 0: return 0
x = int(math.sqrt(n))
while (x+1)*(x+1) <= n: x += 1
while x*x > n: x -= 1
return x
pow = _extended_pow()
def exit(): sys.exit()
このマクロをimportをしている箇所のすぐ下にコピペしてください。
注意点
input = lambda: sys.stdin.readline().rstrip("\r\n")
このような入力高速化をしている場合はcodonではCEになるので削除してください。
なお、CEになるだけでペナはつかないので忘れても気づけると思います。
マクロの使用例
AWC0151_D
pypy
2000ms (26/96 TLE)
https://atcoder.jp/contests/awc0151/submissions/80550855
codon
771ms (AC)
https://atcoder.jp/contests/awc0151/submissions/80550919
ABC391_F
pypy
3000ms (2/61 TLE)
https://atcoder.jp/contests/abc391/submissions/80550914
codon
420ms (AC)
https://atcoder.jp/contests/abc391/submissions/80550926
ACLについて
codonではACLが使えません。
ただ、navel_tosさんのライブラリを使えばpypyでACLを使用していたのと同じコードでcodonでも提出することが出来ます。
ライブラリのgithub
ACLにないhldやsparse tableなどもあるようです。
ShareOJでライブラリを使用する時の注意点
ShareOJ(codon 0.20)では、SegTreeなどの以下の部分でCEを引き起こす場合があります。
self._log = 64 - max(0, self._n - 1).__ctlz__()
前述のマクロを使用している前提で、以下のコードに書き換えてください。
self._log = (self._n - 1).bit_length()
おわりに
Python競プロerの悩みである実行速度をほぼ解決するのがcodonです。
手元で動かすようにするのは少し大変ですが、環境構築をしなくてもTLEを解決する最終手段として、マクロをコピペして提出するという手札を持っておくだけで守られるレートがあるかもしれません。
用法用量を守って正しく乱用してください。