染色的树 0518 美团03

不知道为什么只通过了20%,O(N)级别了,python还是过不了

s = input()
st1 = set()
st2 = set()
st3 = set()
for c in s:
    if c in ['a','e','i','o','u']:
        continue
    for it in st2:
        st3.add(it+c)
    for it in st1:
        st2.add(it+c)
    st1.add(c)
print(len(st2)+len(st3))

改进版本

s = input()
st1 = set()
d = dict() # [str2: lastidx]
alphabetCnt = [[0]*26 for _ in range(len(s))]
for idx,c in enumerate(s):
    if c in ['a','e','i','o','u']:
        continue
    for it in st1:  # 以 c 结尾的长度为 2 的字符串
        str2 = it+c
        if str2 not in d:
            d[str2] = idx
    st1.add(c)
    if idx != 0:
        alphabetCnt[idx] = alphabetCnt[idx - 1]
    alphabetCnt[idx][ord(c)-ord('a')] += 1

res = len(d)
for str2, lastIdx in d.items():
    diffCnt = 0
    for i in range(26):
        if alphabetCnt[-1][i] - alphabetCnt[lastIdx][i] > 0:
            diffCnt += 1
    res += diffCnt
print(res)
from collections import defaultdict
n = int(input())
s = input()
nodes = [0]*(n+1)
for i in range(n):
    if s[i] == "R":
        nodes[i+1] = 1

g = defaultdict(list)
for i in range(n-1):
    u, v = map(int,input().split())
    g[u].append(v)
    g[v].append(u)

cnt = [0]*(n+1)
def dfs(s,cur,last,redCnt):
    global nodes, g
    redCnt += nodes[cur] # s到cur的路径上有redcnt个节点
    if cur!=s:
        cnt[s] += redCnt
    for next in g[cur]:
        if next != last:
            dfs(s,next,cur,redCnt)


for i in range(n):
    curNode = i+1
    dfs(curNode,curNode,-1,0)
    print(cnt[curNode])
# 4
# WRRR
# 1 2
# 2 3
# 2 4
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值