第一题:二叉树含有2个叶结点的非叶子结点个数统计(AC)
m,n = map(int,input().split()) alls = set([i for i in range(1,m+1)]) nleaf = set() from collections import defaultdict dic = defaultdict(list) for _ in range(n): a,b,c = input().split() dic[int(a)].append(int(c)) nleaf.add(int(a)) leaf = alls-nleaf re = 0 for k in dic: if len(dic[k])==2: flag=True for x in dic[k]: if x not in leaf: flag=False if flag: re+=1 print(re)第二题:长度大于1的回文串个数(AC)
s = input() def getC(l,r): count = 0 while l>=0 and r<=len(s)-1 and s[l]==s[r]: if l!=r: count+=1 l-=1 r+=1 return count def getCounts(s): count = 0 for i in range(len(s)): count+=getC(i,i) count+=getC(i,i+1) return count if len(s)==1: print(0) else: re = getCounts(s) print(re)第三题:'a', 'b', 'c', 'x', 'y', 'z'偶数个最长序列长度(AC)
s = input() if len(s)==1: print(0) else: dic = {'a':0,'b':0,'c':0,'x':0,'y':0,'z':0} temp = {(0,0,0,0,0,0):-1} res = 0 for i,char in enumerate(s): if char in dic: dic[char]=(dic[char]+1)%2 idx = tuple(dic.values()) if idx in temp: res = max(res, i-temp[idx]) else: temp[idx]=i else: res=max(res, i-temp[tuple(dic.values())]) print(res)第四题:男女生约会二部图(AC)
man_id = list(map(int,input().split())) woman_id = list(map(int,input().split())) N = int(input()) man_x = dict() woman_x = dict() visited = dict() t = dict() for i in man_id: man_x[i]=-1 for i in woman_id: woman_x[i]=-1 visited[i] = 0 for _ in range(N): a,b = map(int,input().split()) t[(a,b)]=1 def path(u): for v in woman_id: if (u,v) in t and not visited[v]: visited[v]=1 if woman_x[v]==-1: man_x[u]=v woman_x[v]=u return 1 else: if path(woman_x[v]): man_x[u]=v woman_x[v]=u return 1 return 0 def maxMatch(): res = 0 for i in man_id: if man_x[i]==-1: for k in woman_id: visited[k]=0 res+=path(i) return res print(maxMatch())
全部评论
(1) 回帖