AcWing 240. 食物链python3
原题链接
中等
作者:
xanxus1111
,
2020-05-07 16:34:10
,
所有人可见
,
阅读 720
#与根结点的距离 余1可以吃根节点,余2可以被根结点吃 余0是根节点同类
def find(x):
if p[x] != x:
t = find(p[x])
d[x] += d[p[x]]
p[x] = t
return p[x]
if __name__ == "__main__":
res = 0
n,k = map(int,input().split())
p = [i for i in range(n+1)]
d = [0]*(n+1)
for i in range(k):
s = input()
x,y = map(int,s[1:].split())
if x > n or y > n:
res+=1
else:
px, py = find(x), find(y)
if s[0] == '1':
if px == py and (d[x]-d[y])%3:
res+=1
elif px != py :
p[px] = py
d[px] = d[y] - d[x]
else:
if px == py and (d[x] - d[y] -1) % 3:
res+=1
elif px != py :
p[px] = py
d[px] = d[y] - d[x] + 1
print(res)