E - Takahashi Quest Editorial by kyopro_friends


後ろから考え、「最後まで敗北しないためにこの時点で持っている必要のあるポーションの種類と個数」を管理します。

「必要なポーションは可能な限り後で(=後ろから見て最初に)拾うのが最適である」ということから、ポーションを見つけたときは必要なポーションであれば必ず拾うとしてよいです。

実装例(Python)

from collections import defaultdict
N=int(input())
Q=[tuple(map(int,input().split())) for _ in range(N)]

req=defaultdict(int)
crr=0
ans=0
choice=[]
for t,x in Q[::-1]:
  if t==1:
    if req[x]:
      req[x]-=1
      crr-=1
      choice.append(1)
    else:
      choice.append(0)
  elif t==2:
    req[x]+=1
    crr+=1
    ans=max(ans,crr)

if sum(req.values())==0:
  print(ans)
  print(*choice[::-1])
else:
  print(-1)

posted:
last update: