Задача А
def state(s):
code = {'1':0b01, '2':0b10, '3':0b11}
r = 0
for c in s:
r = (r << 2) | code[c]
return r
switch = [lambda x: (x & 0x3FFC0) | ((x & 0x0000F) << 2) | ((x & 0x00030) >> 4),
lambda x: (x & 0x3FFC0) | ((x & 0x0003C) >> 2) | ((x & 0x00003) << 4),
lambda x: (x & 0x3F03F) | ((x & 0x003C0) << 2) | ((x & 0x00C00) >> 4),
lambda x: (x & 0x3F03F) | ((x & 0x00F00) >> 2) | ((x & 0x000C0) << 4),
lambda x: (x & 0x00FFF) | ((x & 0x0F000) << 2) | ((x & 0x30000) >> 4),
lambda x: (x & 0x00FFF) | ((x & 0x3C000) >> 2) | ((x & 0x03000) << 4),
lambda x: (x & 0x3CF3C) | ((x & 0x030C0) >> 6) | ((x & 0x00003) << 12),
lambda x: (x & 0x3CF3C) | ((x & 0x000C3) << 6) | ((x & 0x03000) >> 12),
lambda x: (x & 0x33CF3) | ((x & 0x0C300) >> 6) | ((x & 0x0000C) << 12),
lambda x: (x & 0x33CF3) | ((x & 0x0030C) << 6) | ((x & 0x0C000) >> 12),
lambda x: (x & 0x0F3CF) | ((x & 0x30C00) >> 6) | ((x & 0x00030) << 12),
lambda x: (x & 0x0F3CF) | ((x & 0x00C30) << 6) | ((x & 0x30000) >> 12)]
final = set([state("111222333"), state("111333222"), state("222111333"),
state("222333111"), state("333111222"), state("333222111"),
state("123123123"), state("132132132"), state("213213213"),
state("231231231"), state("312312312"), state("321321321")])
start = state(raw_input() + raw_input() + raw_input())
r = set()
q = [start]
c = 0
found = False
while q != []:
nq = []
for s in q:
r.add(s)
if s in final:
found = True
break
for i in switch:
ns = i(s)
if ns not in r:
nq.append(ns)
if found:
break
q = nq
c += 1
print c if found else '-'
Задача В
def GCD(a, b):
a = abs(a); b = abs(b)
a, b = max(a, b), min(a, b)
while b > 0:
a, b = b, a % b
return a
def line(p, q):
dx = q[0] - p[0]; dy = q[1] - p[1]
d = GCD(dx, dy)
if d > 0:
dx = dx // d; dy = dy // d
if dy < 0:
dx = -dx; dy = -dy
elif dy == 0:
dx = abs(dx)
return dx, dy
def flat(a):
if a == []: return
t = a[0]; c = 1
for x in a[1:]:
if t == x:
c += 1
else:
yield c
t = x; c = 1
yield c
N = input()
P = []
for i in range(N):
P.append(tuple(int(s) for s in raw_input().split()))
if N < 3:
print N
else:
m = 0
for i in range(N - 2):
p = P[i]
lines = [line(p, q) for q in P[i + 1:]]
v = lines.count((0, 0))
f = sorted(k for k in lines if k != (0, 0))
m = max(m, 1 + v + (max(flat(f)) if len(f) > 0 else 0))
print m
Задача С
a = raw_input()
n = input()
person = {}
for i in range(n):
s = raw_input().split()
for p in s:
if p not in person:
person[p] = {"parents":set(), "children":set()}
for p in s[0:2]:
person[p]["children"] |= set(s[2:])
for p in s[2:]:
person[p]["parents"] |= set(s[0:2])
parents = person[a]["parents"] if a in person else set()
grandparents = set.union(*[person[p]["parents"] for p in parents]) if len(parents) > 0 else set()
uncles = (set.union(*[person[p]["children"] for p in grandparents]) - parents) if len(grandparents) > 0 else set()
cousins = set.union(*[person[p]["children"] for p in uncles]) if len(uncles) > 0 else set()
print len(cousins)