小蓝要用七段码数码管来表示一种特殊的文字。
上图给出了七段码数码管的一个图示,数码管中一共有 7 段可以发光的二极管,分别标记为 a, b, c, d, e, f, g。
小蓝要选择一部分二极管(至少要有一个)发光来表达字符。
在设计字符的表达时,要求所有发光的二极管是连成一片的。
例如:b 发光,其他二极管不发光可以用来表达一种字符。
例如:c 发光,其他二极管不发光可以用来表达一种字符。
这种方案与上一行的方案可以用来表示不同的字符,尽管看上去比较相似。
例如:a, b, c, d, e 发光,f, g 不发光可以用来表达一种字符。
例如:b, f 发光,其他二极管不发光则不能用来表达一种字符,因为发光的二极管没有连成一片。
思路
并查集。。。(练了快一个月,竟然还是不熟。。。阿西吧)
from itertools import combinations
# 并查集模板
class UnionFind:
def __init__(self, size: int):
self.count = size
self._father = {}
for i in range(size):
self._father[i] = i
self.weight = [1] * size
def add(self, x):
if x not in self._father:
self._father[x] = x
def find(self, x):
root = x
while self._father[root] != root:
root = self._father[root]
# 路径压缩
while x != root:
origin_root = self._father[x]
self._father[x] = root
x = origin_root
return root
def merge(self, x: int, y: int):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
if self.weight[root_x] < self.weight[root_y]:
root_x, root_y = root_y, root_x
self._father[root_y] = root_x
self.weight[root_x] += self.weight[root_y]
self.count -= 1
if root_x == root_y:
return False
def is_connected(self, x, y):
return self.find(x) == self.find(y)
res = 0
list1 = [0, 1, 2, 3, 4, 5, 6]
a = len(list1)
for i in range(1, a+1):
for item in (combinations(list1, i)):
n = len(item)
uf = UnionFind(n)
for j in range(n):
for k in range(j+1,n):
if abs(item[j] - item[k]) == 1 or (item[j] == 0 and item[k] == 5) or (item[j] == 1 and item[k] == 6) or (item[j] == 2 and item[k] == 6) or (item[j] == 4 and item[k] == 6):
uf.merge(j, k)
if uf.count == 1:
res += 1
print(res)