链接: 6265. 统计相似字符串对的数目
class Solution:
def similarPairs(self, words: List[str]) -> int:
c = Counter()
for w in words:
c[''.join(sorted(set(w)))] += 1
ans = 0
for v in c.values():
ans += v*(v-1)//2
return ans
链接: 6266. 使用质因数之和替换后可以取到的最小值
幸好之前写了个取质因数的模板,直接复制过来按题意要求模拟。
直接找质因数
,看似2重循环也没判断质数,实际上由于因数从2开始变大,且每次把每个数除完,因此不会取到合数(会实现把这个合数的因子取完),且复杂度就是sqrt(n)。
class Solution:
def smallestValue(self, n: int) -> int:
while True:
x, s, i = n, 0, 2
while i * i <= x:
while x % i == 0:
s += i
x //= i
i += 1
if x > 1: s += x
if s == n: return n
n = s
def tag_primes_euler(n): # 返回一个长度n+1的数组p,如果i是质数则p[i]=1否则p[i]=0
primes = [1]*(n+1)
primes[0] = primes[1] = 0 # 0和1不是质数
ps = [] # 记质数
for i in range(2,n+1):
if primes[i]:
ps.append(i)
for j in ps:
if j*i>n:
break
primes[j*i] = 0
if i%j == 0:break
# print(ps)
return primes
primes = tag_primes_euler(10**5+5)
@cache
def get_prime_reasons(x):
if x == 1:
return Counter()
if primes[x]:
return Counter([x])
for i in range(2,int(x**0.5)+1):
if x % i == 0:
return get_prime_reasons(i) + get_prime_reasons(x//i)
class Solution:
def smallestValue(self, n: int) -> int:
while n :
c = get_prime_reasons(n)
s = 0
for k,v in c.items():
s += k*v
if s == n:
return s
n = s
return n
链接: 6267. 添加边使所有节点度数都为偶数
class Solution:
def isPossible(self, n: int, edges: List[List[int]]) -> bool:
g = [set() for _ in range(n)]
for u,v in edges:
u-=1
v-=1
g[u].add(v)
g[v].add(u)
ji,ou = [],[]
for u in range(n):
if len(g[u]) & 1:
ji.append(u)
else:
ou.append(u)
if len(ji)>=5:
return False
if not ji :
return True
if len(ji)&1:
return False
if len(ji) == 2:
a,b = ji
if a not in g[b]:
return True
for u in ou:
if u not in g[a] and u not in g[b]:
return True
return False
if len(ji) == 4:
a,b,c,d = ji
if a not in g[b] and c not in g[d]:
return True
if a not in g[c] and b not in g[d]:
return True
if a not in g[d] and c not in g[b]:
return True
return False
链接: 6268. 查询树中环的长度
正经LCA
class Solution:
def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
def calc(a,b):
ans = 1
while a!=b:
if a > b:
a,b = b,a
ans += 1
b //= 2
return ans
return [calc(a,b) for a,b in queries]
class Solution:
def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
m = len(queries)
ans = []
def calc(a,b):
if a > b:
a,b = b,a
s,p = set(),[]
while a:
s.add(a)
a //= 2
while b:
if b in s:
return len(p) + len([a for a in s if a>b])+1
p.append(b)
b //= 2
for a,b in queries:
ans.append(calc(a,b))
return ans
两个点同时走
class Solution:
def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:
def calc(a,b):
if a > b:
a,b = b,a
s,p = set(),0
while b:
if a:
s.add(a)
a //= 2
if b in s:
return p + len([a for a in s if a>b])+1
p += 1
b //= 2
return p
return [calc(a,b) for a,b in queries]