def solve(a,b,c,d):
cap = [0,a,b,c]
min_state = (0,0,0,c)
start = (0,0,0,c)
vis = set((0,0,c))
water_state = PriorityQueue()
water_state.put(start)
whilenot water_state.empty():
now = water_state.get()
if d innow[1:]:print(now);return(now[0],d)
ifabs(d-min_state[3])>abs(d-now[3]):min_state=nowfor i in range(1,4):
for j in range(1,4):
if i!=j:
ifnow[i]==0ornow[j]==cap[j]:continue
amount = min(now[i],cap[j]-now[j])
new = list(now)
new[0]+=amount;new[i]-=amount;new[j]+=amount
new = tuple(new)
ifnew[1:] notin vis:
vis.add(new[1:])
water_state.put(new)
possible_d = min_state[1]
for x in min_state[1:]:
possible_d = min(possible_d,x,key = lambda y:abs(y-d))
return (min_state[0],possible_d)
print(solve(1,12,15,7))
defsolve(graph,w,h,n):
direction = {0:(0,0),1:(1,0),2:(0,1),3:(-1,0),4:(0,-1)}
defconstruct(graph):
nodes_table = {}
for i in range(w):
for j in range(h):
p = (i,j)
nodes_table[p] = []
if graph[i][j]=='#':continuefor k in range(5):
adj = walk(p,k)
if check(adj):
nodes_table[p].append(adj)
return nodes_table
defwalk(p,i):
x,y = p
return (x+direction[i][0],y+direction[i][1])
defcreate_nodes(q,now,new,cur):if cur==n:
new=tuple(new)
if check_notswap(now,new) and new notin states:
states.add(new)
q.append(new+(now[n]+1,))
returnfor next in adj_table[now[cur][:n]]:
new.append(next)
create_nodes(q,now,new,cur+1)
new.pop()
defcheck(next):
x,y = next
if x<w and x>0and y<h and y>0and graph[x][y]!='#':returnTruereturnFalsedefcheck_notswap(now,new):for i in range(n):
for j in range(i+1,n):
if new[i]==new[j] or (now[i],now[j])==(new[j],new[i]):returnFalsereturnTruedefsatisfy(now):for i in range(n):
if now[i]!=capital_pos[i]:returnFalsereturnTruedefsearch_capital(ans_pos,capital_pos,graph):for i in range(w):
for j in range(h):
if str.islower(graph[i][j]):ans_pos[ord(graph[i][j])-ord('a')] = (i,j)
elif str.isupper(graph[i][j]):capital_pos[ord(graph[i][j])-ord('A')] = (i,j)
states = set()
ans_pos,capital_pos = [0]*n,[0]*n
search_capital(ans_pos,capital_pos,graph)
adj_table = construct(graph)
q = deque()
start = tuple([p for p in ans_pos]+[0])
states.add(start[:n])
q.append(start)
while len(q):
now = q.popleft()
if satisfy(now):return now
create_nodes(q,now,[],0)
defprocess():
line = input().split(' ')
h,w,n = [int(x) for x in line]
graph = []
for i in range(w):
line = input()
graph.append(line)
print(solve(graph,w,h,n))
process()