結果
| 問題 |
No.3121 Prime Dance
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-04-20 04:27:23 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 3,123 bytes |
| コンパイル時間 | 106 ms |
| コンパイル使用メモリ | 12,672 KB |
| 実行使用メモリ | 13,056 KB |
| 最終ジャッジ日時 | 2025-04-20 04:27:26 |
| 合計ジャッジ時間 | 2,573 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 17 WA * 4 |
ソースコード
from heapq import heappush, heappop
from collections import deque
def solve():
H,W = map(int,input().split())
sx,sy = map(lambda x:int(x)-1, input().split())
gx,gy = map(lambda x:int(x)-1, input().split())
A = [list(input().rstrip()) for _ in range(H)]
dx = gx - sx
dy = gy - sy
vis = [[False]*W for _ in range(H)]
dq = deque([(sx,sy)])
vis[sx][sy] = True
while dq:
x,y = dq.popleft()
for dxx,dyy in ((1,0),(-1,0),(0,1),(0,-1)):
nx,ny = x+dxx, y+dyy
if 0<=nx<H and 0<=ny<W and not vis[nx][ny] and A[nx][ny] != '#':
vis[nx][ny] = True
dq.append((nx,ny))
canV = any(vis[i][j] and i+1<H and vis[i+1][j] for i in range(H) for j in range(W))
canH = any(vis[i][j] and j+1<W and vis[i][j+1] for i in range(H) for j in range(W))
if not vis[gx][gy]:
print(-1)
return
pareto = [[[] for _ in range(W)] for __ in range(H)]
pq = [(0,0,0,sx,sy)]
pareto[sx][sy].append((0,0))
while pq:
_, v, h, x, y = heappop(pq)
dominated = False
for vv,hh in pareto[x][y]:
if vv<=v and hh<=h and (vv,hh)!=(v,h):
dominated = True; break
if dominated: continue
for dxx,dyy in ((1,0),(-1,0),(0,1),(0,-1)):
nx,ny = x+dxx, y+dyy
if not (0<=nx<H and 0<=ny<W and A[nx][ny] != '#'): continue
nv, nh = v + (1 if dxx!=0 else 0), h + (1 if dyy!=0 else 0)
skip = False
remove = []
for idx,(vv,hh) in enumerate(pareto[nx][ny]):
if vv<=nv and hh<=nh:
skip = True; break
if nv<=vv and nh<=hh:
remove.append(idx)
if skip: continue
for idx in reversed(remove):
pareto[nx][ny].pop(idx)
pareto[nx][ny].append((nv,nh))
heappush(pq, (nv+nh, nv, nh, nx, ny))
MAXP = 200000
is_prime = [True]*(MAXP+1)
is_prime[0]=is_prime[1]=False
for i in range(2,MAXP+1):
if is_prime[i]:
for j in range(i*i, MAXP+1, i):
is_prime[j] = False
def min_pad(big, small, delta, can_loop):
if not can_loop:
return 0 if (big>=2 and small>=2 and is_prime[big] and is_prime[small]) else None
for t in range(0, MAXP-big+1):
p = big + t
q = p - delta
if q<2: continue
if is_prime[p] and is_prime[q]:
return t
return None
ans = None
for V,H in pareto[gx][gy]:
if V<abs(dx) or (V-dx)%2!=0: continue
if H<abs(dy) or (H-dy)%2!=0: continue
A0 = (V + dx)//2
B0 = (V - dx)//2
C0 = (H + dy)//2
D0 = (H - dy)//2
pad_v = min_pad(max(A0,B0), min(A0,B0), abs(dx), canV)
pad_h = min_pad(max(C0,D0), min(C0,D0), abs(dy), canH)
if pad_v is None or pad_h is None:
continue
total = (V+H) + 2*pad_v + 2*pad_h
if ans is None or total<ans:
ans = total
print(ans if ans is not None else -1)
solve()