【发布时间】:2020-01-31 12:49:28
【问题描述】:
最近在尝试实现google kickstater 2019编程题的解决方案,按照分析说明尝试实现Round E的Cherries Mesh。 这是问题和分析的链接。 https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050edb/0000000000170721
这是我实现的代码:
t = int(input())
for k in range(1,t+1):
n, q = map(int,input().split())
se = list()
for _ in range(q):
a,b = map(int,input().split())
se.append((a,b))
l = [{x} for x in range(1,n+1)]
#print(se)
for s in se:
i = 0
while ({s[0]}.isdisjoint(l[i])):
i += 1
j = 0
while ({s[1]}.isdisjoint(l[j])):
j += 1
if i!=j:
l[i].update(l[j])
l.pop(j)
#print(l)
count = q+2*(len(l)-1)
print('Case #',k,': ',count,sep='')
这通过了示例用例,但没有通过测试用例。据我所知,这应该是正确的。我做错了吗?
【问题讨论】:
-
您的不相交集实现非常缓慢,但看起来是正确的。但是,您计算的计数不正确。应该是
count = n + len(l) - 2 -
有没有一种有效的方法来实现不相交的数据结构?用蟒蛇。或者我应该依赖像 cpp 或 java 这样的编译语言吗?
-
当然你可以在 python 中非常有效地做到这一点。我不记得在 SO 上看到过一个非常好的例子,所以如果你愿意,我会在几个小时内给出一个答案。既然您正在练习,也许您想先尝试遵循维基百科的文章:en.wikipedia.org/wiki/Disjoint-set_data_structure
标签: python algorithm data-structures disjoint-sets disjoint-union