注意到每个customer最多只能有一种奶昔是”malted”的,这点是解决这题的关键。可以推出以下结论:
针对分析,我们处理第三点,逻辑流程如下:
主循环体退出的条件: 客户列表为空或者已经不存在只偏好某一种”malted”奶昔的客户 。
备注:因为每次循环都会减少总体奶昔的数量,所以上次还存在多种偏好的customer到了下次循环的时候偏好就有可能只剩一种了,这个是动态变化的。
写得稀碎的python:
with open("B-large-practice.in") as f:
C = int(f.readline())
for i in range(C):
N = int(f.readline())
M = int(f.readline())
l = []
for j in range(M):
tmp = {}
line = f.readline().strip().split()
for k in range(int(line[0])):
tmp[int(line[2 * k + 1])] = int(line[2 * k + 2])
l.append(tmp)
ans = {}
# solution logic insert below
possible = True
while len(l) and possible:
new_malted = None
for c in l:
if len(c) > 1:
continue
if c[c.keys()[0]] == 1:
ans[c.keys()[0]] = 1
new_malted = c.keys()[0]
break
elif c.keys()[0] in ans:
possible = False
break
if new_malted is None:
break
del_list = []
for c in l:
if new_malted in c:
if c[new_malted]:
del_list.append(c)
continue
else:
del c[new_malted]
if len(c) == 0:
possible = False
break
for c in del_list:
l.remove(c)
# output result
res = "Case #{0}:".format(i + 1)
if not possible:
res += " IMPOSSIBLE"
else:
for i in range(N):
if i + 1 in ans:
res += " 1"
else:
res += " 0"
print res