算法题目

-- coding: utf-8 --

"""
Created on Wed Jun 1 15:34:00 2022

@author: guess who i am
"""

说明:

1 本文共一百八九十道题,涵盖了截止2022.6.30我在网上所见到的所有题,真正的最全题库,只有答案没有题目。

https://www.online1987.com/shezhao/ 这个网站是实时更新的,很全。但是题解是付费才能看的。有的冷门题目,

可以到这个网站上搜到

2 本文题解有的仍需一些小的改动,才可以跑起来

3 考试按正确率给分,超时好像没影响

4 考试按最后一次提交的正确率给分,而不是取曾经的最高正确率

5 考试每题需点击保存并提交,否则不计分

6 有些题解是我根据别的语言翻译过来的,所以在某些自带函数的名称及用法上,有待规范python的语法

7 需要注意代码查重率的问题!!!

8 需要练习acm模式下的输入输出问题

9 有时,200分的题目也会出在100分的位置上,无形中提高了整个考试的难度

10 二叉树的题目比较少,我印象中顶多6-10道左右,但是万一抽到了,要会配置acm模式下的二叉树

11 分数还是高点好,网上有案例考了150-200分之间,最后审批被卡的

100分题

1 找朋友

N个小朋友站成一对,第i个小朋友的身高为height[i],第i个小朋友可以看到的第一个比自己

身高更高的小朋友j,那么j是i的好朋友(要求j>i)。 请重新生成一个列表,对应位置的输出是

每个小朋友的好朋友位置,如果没有看到好朋友,请在该位置用0代替

小朋友人数范围是【0, 40000】

输入描述:第一行输入N,表示有N个小朋友; 第二行输入N个小朋友的身高Height[i], 都是整数

输出描述: 输出N个小朋友的好朋友的位置

示例:

2

100 95

输出: 0 0

def solve(self, n, nums):
n=int(input())
height=list(int(input().split(" ")))
ans=[0]*n
for i in range(n):
idx=0
for j in range(i+1, n):
if height[i]<height[j]:
idx=j
break
ans[i]=idx;
for i in range(len(ans)): # 输出的是单个数,用空格分开,而不是一个数组
if i!=len(ans)-1:
print(ans[i]+" ")
else:
print(arr[i])

2 统计射击比赛成绩

给定一个射击比赛成绩单,包含多个选手若干射击的成绩分数,请对每个选手按其最高3个分数之和

进行降序排名,输出降序排名后的选手ID序列,条件如下:

1. 一个选手可以有多个射击成绩的分数,且次序不固定

2. 如果一个选手成绩少于3个, 则认为选手的所有成绩无效,排名忽略该选手

3. 如果选手的成绩之和相等,则成绩之和相等的选手按照其ID降序排列

输入描述

第一行,一个整数N, 表示该场比赛总共进行了N次射击,产生N个成绩分数(2<=N<=100)

第二行,一个长度为N的整数序列,表示参与每次射击的选手ID(0<=ID<=99)

第三行,一个长度为N的整数序列,表示参与每次射击的选手对应的成绩(0<=成绩<=100)

输出描述

符合题设条件的降序排名后的选手ID序列

输入

13

3,3,7,4,4,4,4,7,7,3,5,5,5

53,80,68,24,39,76,66,16,100,55,53,80,55

输出

5,3,7,4

说明

该场射击比赛进行了13次,参赛的选手为{3,4,5,7}。

3号选手成绩:53,80,55,最高3个成绩的和为:80+55+53=188。

4号选手成绩:24,39,76,66,最高3个成绩的和为:76+66+39=181。

5号选手成绩:53,80,55,最高3个成绩的和为:80+55+53=188。

7号选手成绩:68,16,100,最高3个成绩的和为:100+68+16=184。

比较各个选手最高3个成绩的和,有3号=5号>7号>4号,由于3号和5号成绩相等且ID号5>3,所以输出为:5,3,7,4。

def func(N: int, id: list, grade: list):
dic={} # 记录每一个人的ID以及对应的成绩
for i in range(N):
list1=[] # 记录每一个人的成绩
for j in range(N):
if id[j]==id[i]:
list1.append(grade[j])
dic[id[i]]=list1
keys_list=list(dic.keys()) # 选手的ID
values_list=list(dic.values()) # 选手的成绩

for k in range(len(values_list)):
    if len(values_list[k])<3:
        dic.pop(keys_list[k]) # 射击小于3次的排除
    else:
        values_list[k].sort(reverse=True)
        value=sum(values_list[k][:3])
        dic[keys_list[k]]=value
list2=sorted(dic.items(), key=lambda x:(x[1], x[0]), reverse=True)
list2=[str(l[0]) for l in list2]
return ",".join(list3)

3 句子重量

每个句子由多个单词组成,句子中的每个单词的长度都可能不一样,我们假设每个单词的长度Ni为

该单词的重量,你需要做的就是给出整个句子的平均重量V

示例:

输入: Who Love Solo 输出: 3.67

def func():
s=input().split(" ")
sum=0
for i in s:
sum+=len(i)
print('%.2f' %(sum/len(list))) # 或许可以用round()来表示
if name=="main":
func()

4 金字塔

申请一个长度n+1的数组,保存下级对上级上交的收入,存储在上级对应的下标中

n=int(input())
nums=[list(map(int, input().split())) for _ in range(n)]
nums=sorted(nums, key=lambda x: x[1], reverse=True)
dp=[0](n+1)
start=0
end=0
for i, j, m in nums: # 这个题解好像有点问题
end=max(i, end)
start=min(j, start)
dp[j]+=((m+dp[i])//100)
15
print(start+' '+dp[start])

5 翻牌求最大分

nums=int(input().split(","))
ans=dp[0]
for i in range(n):
if i1:
dp[1]=max(dp[0]+[i], 0)
ans=max(dp[1], 0)
elif i
2:
dp[2]=max(dp[2], 0)
else:
dp[i]=max(dp[i-3], dp[i-1]+arr[i])
ans=max(dp)
print(ans)

6 输出指定字母在字符串中的索引

给定一个字符串,把字符串按照大写在前,小写在后排序,输出排好后的第K个字母在原来字符串的索引

相同字母输出第一个出现的位置

输入 hAkDAjByBq 4; 输出: 6

s, k=map(input().split())
s_upper=""
s_lower=""
for ch in s:
if ch>='A' and ch<='Z':
s_upper+=ch
else:
s_lower+=ch
s_upper.sort()
s_lower.sort()
s_new=s_upper+s_lower
ans=s.find(new[k-1])
print(ans)

7 篮球比赛

nums=list(map(int, input().split()))
candidates=[]
for a in range(6):
for b in range(a+1,7):
for c in range(b+1,8):
for d in range(c+1,9):
for e in range(d+1,10):
candidates.append((nums[a], nums[b], nums[c], nums[d], nums[e]))
ans=abs(sum(nums)-2sum(candidates[0]))
for i in candidates:
if abs(sum(nums)-2
sum(i))<ans:
ans=abs(sum(nums)-2*sum(i))
print(ans)

第二种

ints=list(map(int, input().split()))
count=0
for i in range(10):
count+=ints[i]
temp=0
ans=float('inf')
for i in range(6):
for j in range(i+1, 7):
for k in range(j+1, 8):
for l in range(k+1, 9):
for m in rnage(l+1, 10):
temp=ints[i]+ints[j]+ints[k]+ints[l]+ints[m]
ans=min(ans, abs(count-2*temp))
print(ans)

8 最长子字符串的长度

s=input()
count=0
idxs=[]
for i in range(len(s)):
if s[i]'o':
count+=1
idxs.append(i)
if count%2
0:
print(len(s))
ans=0
start=idxs[0]
end=idxs[-1]
ans=max(end-start+1, len(s)-j+i+1)
for i in range(len(idxs)):
for j in range(i+1, len(idxs), 2):
curlen=max(j-i+1, len(s)-j+i+1)
ans=max(ans, curlen)
print(ans)

9 VLAN资源池

nums=input().split(',')
x=int(input())
ans=[]
for num in nums:
frame=list(map(int, num.split('-')))
if len(frame)1:
ans.append(frame[0])
else:
start=frame[0]
end=frame[1]
for i in range(start, end+1):
if i
x:
continue
ans.append(i)
ans.sort()
anss=[]
start=end=0
for i in range(1, len(ans)):
if ans[i]ans[end]+1:
end=i
else:
if start
end:
anss.append(str(ans[start]))
else:
anss.append(str(ans[start])+'-'+str(ans[end]))
start=end=i
print(",".join(anss))

10 数字反转打印 # 金字塔形状的

def helper(n):
if n1:
return 1
else:
return helper(n-1)+n-1
n=int(input())
nums=[]
for i in range(1, n+1):
row=[]
first=helper(i)
space=(n-i)' '
row.append(space)
for j in range(i):
temp=''
first+=1
temp=first+'
**'
row.append(temp[:4])
if j!=i-1:
row.append(" ")
if i%2
0:
row=reversed(row)
nums.append(row)
for num in nums:
ans=''
for i in range(len(num)):
ans+=num[i]
print(ans)

11 求字符串中所有整数的最小和

s=input()
positive=[]
negative=[]
while i<len(s):
if s[i]>='0' or s[i]<='9':
positive.append(i)
else:
if s[i]=="-":
rest=s[i+1:]
temp=''
for ch in rest:
if ch>='0' and ch<='9':
temp+=ch
else:
break
if len(temp)!=0:
negative.append("-"+temp)
i=i+len(temp)
i+=1
positive.extend(negative)
ans=0
for x in positive:
ans=ans+int(x)
print(ans)

12 求解连续数列

x=input().split()
sum, n=x[0], x[1]
temp=sum-n*(n-1)/2
if temp<=0 or temp%n!=0:
print(-1)
start=temp/n
for i in range(n):
print(start+i)
print(' ')

13 判断一组不等式是否满足约束并输出最大差

s=input().split(',')
n=len(s)
equals=s[n-1].split(',')
targets=s[n-2].split(',')
variables=s[n-3].split(',')
for i in range(len(equals)):
targets[i]=float(targets[i])
for i in range(len(variables)):
variables[i]=int(variables[i])
coefficients=[]
for i in range(len(equals)):
for j in range(len(variables)):
coefficients[i][j]=s[i].split(',')[j]
ans=True
maxdiff=0
for i in range(len(equals)):
cursum=0
flag=True
for j in range(len(variables)):
cursum+=coefficients[i][j]*variables[j]
maxdiff=max(maxdiff, cursum-targets[i])
if equals[i]'>':
flag=cursum>targets[i]
elif equals[i]
'>=':
flag=cursum>=targets[i]
elif equals[i]'<':
flag=cursum<targets[i]
elif equals[i]
'=':
flag=cursumtargets[i]
if flag
False:
ans=False
print(ans+" "+int(maxdiff))

14 字符串分割

def helper(s):
small=large=0
for i in range(len(s)):
if s[i]>='a' and s[i]<='z':
small+=1
elif s[i]>='A' and s[i]<='Z':
large+=1
if small>large:
return s.lower()
elif small<large:
return s.upper()
else:
return s
k=int(input())
s=input().split('-')
ipt=[]
temp=[]
for i in range(1, len(s)):
temp.append(s[i])
tem="".join(temp)
while len(tem)>0:
if len(tem)>=k:
ipt.append(tem[0:k])
tem=tem[k:]
else:
ipt.append(tem)
tem=""
ans=[]
ans.append(s[0])
ans.append("-")
for i in range(len(ipt)):
if i!=len(ipt)-1:
ans.append(helper(ipt[i]))
ans.append("-")
else:
ans.append(helper(ipt[i]))
print("".join(ans))

15 字符串简单数据解压缩

s=input()
n=len(s)
ans=[]
temp=""
count=""
for i in range(n):
if 'a'<=s[i]<='z' or 'A'<=s[i]<='Z':
temp+=s[i]
elif s[i].isdigit():
count+=s[i]
ans.append((temp, int(count)))
temp=""
count=""
ans=sorted(ans, key=lambda x: x[1], x[0])
print("".join([temp*count for temp, count in ans]))

16 表达式括号匹配

s=input()
stack=[]
ans=0
for ch in s:
if ch"(":
stack.append(ch)
elif ch
")":
if stack and stack[-1]=="(":
ans+=1
stack.pop()
else:
break
if stack:
ans=-1
print(ans)

17 括号匹配

s=input()
stack=[]
flag=False
for ch in s:
if ch in "{[(":
stack.append(ch)
elif ch in "}])":
if stack and ((stack[-1]"{" and ch"}") or (stack[-1]"[" and ch"]") or
(stack[-1]"(" and ch")")):
flag=True
stack.pop()
else:
break
if stack:
flag=False
print("true" if flag==True else "false")

18 最大括号深度

s=input()
n=len(s)
stack=[]
ans=0
for i in range(n):
if s[i] in '{[(':
stack.append(s[i])
ans=max(ans, len(stack))
else:
if stack and ((stack[-1]"{" and s[i]"}") or (stack[-1]"[" and s[i]"]") or
(stack[-1]"(" and s[i]")")):
continue
else:
break
if i==len(s)-1 and not stack:
print(ans)
else:
print(0)

19 矩阵最大值

n=int(input())
ans=0
for i in range(n):
nums=list(map(int, input().split()))
for j in range(n):
ch=list_to_string(grids[i], j) # 这里的自带函数,需要改成Python中的,查一查吧
num=bin_to_integer(ch)
nums.append(num)
max1=max(nums)
ans+=max1
print(ans)

20 免单统计

n=int(input())
nums=[]
for _ in range(n):
nums.append(input())
ans=0
dic={}
for time in nums:
prev, s=time.split('.')
if prev not in dic:
dic[prev]={'val'😒, 'count':1}
else:
if dic[prev]["val"]==s:
dic[prev]["count"]+=1
elif dic[prev]["val"]>s:
dic[prev]["val"]=s
dic[prev]["count"]=1
ans=sum(time["count"] for time in dic.values())
print(ans)

21 求满足条件的最长子串的长度

def check(str):
word=0
num=0
for ch in str:
if ch.isalpha():
word+=1
if word>1:
return False
else:
num+=1
return (num>0 and word1)
s=input()
n=len(s)
if n
1:
print(-1)
ans=-1
start, end=0, 1
while start<n:
str=s[start: end]
if check(str):
ans=max(ans, len(s))
end+=1
else:
start+=1
print(ans)

22 流水线

def func(m, n, time):
time=time.sort()
sum=[0]m
for i in range(n):
sum[i%m]+=time[i] # 把任务安排进去,求每一个流水线的总时长
ans=0
for j in range(m):
ans=max(ans, sum[j]) # 比较得出总时长最长的流水线
return ans
m, n=int(input()), int(input())
time=[0]
n
for i in range(n):
time[i]=int(input().split())
print(func(m, n, time))

23 两数之和绝对值最小

nums=list(map(int, input().split(" ")))
n=len(nums)
for i in range(n):
for j in range(n):
ans=min(ans, abs(nums[i]+nums[j]))
print(ans)

24 小朋友排队

h, m=map(int, input().split())
nums=list(map(int, input().split()))
nums=sorted(nums, key=lambda x: (abs(x-h), x)) # 第一排序条件是身高差,第二是身高本身
print(" ".join(map(str, nums)))

25 约瑟夫问题

nums=list(map(int, input().split()))
m=int(input())
ans=[]
idx=0
outpos=1
while len(nums)>0:
if idxlen(nums)-1:
idx=0
if outpos%m
0:
m=nums.pop(idx)
ans.append(m)
outpos=1
else:
idx+=1
outpos+=1
print(",".join(str(x) for x in ans))

26 堆栈中的剩余数字

nums=list(map(int, input().split()))
ans=[]
while len(nums)>0:
num=nums[0]
while num:
if not ans:
ans.append(num)
else:
cursum=0
for i in range(len(ans)-1, -1, -1):
cursum+=ans[i]
if cursum==num:
ans=ans[:-i]
ans.append(2*num)
else:
ans.append(num)
print(" ".join([str(x) for x in reversed(ans)]))

27 数组组成的最小数字

nums=list(input().split(","))
nums=nums.sort()
length=len(nums)
if length<3:
n=length
else:
n=3
def check(nums, n):
if n1:
return nums[0]
elif n
2:
ans1=int(nums[0]+nums[1])
ans2=int(nums[1]+nums[0])
return min(ans1, ans2)
else:
temp=nums[:]
min3=temp[:3].sort()
ans=''
for x in min3:
ans+=x
return ans
print(check(nums, n))

28 一种字符串压缩表示的解压

s=input()
ans=[]
count=0
for ch in s:
if not ((ch>='a' and ch<='z') or (ch>='3' and ch<='9')):
print("!error")
for i in range(len(s)-1):
if (s[i]>='a' and s[i]<='z') and s[i]s[i+1]:
ans.append(s[i])
ans.append(s[i+1])
if (s[i]>='a' and s[i]<='z') and s.count(s[i])
1:
ans.append(s[i])
if (s[i]>='3' and s[i]<='9') and (s[i+1]>='a' and s[i+1]<='z'):
count=int(s[i])
for _ in range(count):
ans.append(s[i+1])
print("".join(ans))

29 消消乐游戏

s=input()
ans=[]
for ch in s:
if len(ans)0:
ans.append(ch)
elif ch
ans[-1]:
ans.pop()
else:
ans.append(ch)
if ans:
print(len(ans))
else:
print(0)

30 最大矩阵和

m,n=map(int, input().split())
nums=[]
for i in range(m):
nums.append(list(map(int, input().split())))
ans=0
for r1 in range(m):
for c1 in range(n):
for r2 in range(r1, m):
cursum=0
for c2 in range(c1, n):
rowindex=r2
while rowindex>=r1:
cursum+=nums[rowindex][c2]
rowindex-=1
ans=max(ans, cursum)
print(ans)

31 找出符合要求的字符串子串

s1=input()
s2=input()
ans={}
s2.sort()
for ch in s2:
if ch in s1:
ans[ch]+=1
for key, value in ans.items():
if value==1:
print("".join(key))

32 单词接龙

k=int(input())
n=int(input())
words=[]
for _ in range(n):
words.append(input())
ans=words[k]
words.remove(words[k])
for i in range(n-1):
candidates=[]
length=[]
for word in words:
if word.startswith(ans[-1]):
candidates.append(word)
length.append(len(word))
if len(candidates)!=0:
max_len=max(length)
if length.count(max_len)1:
ans+=candidates[length.find(max_len)]
words.remove(candidates[length.find(max_len)])
else:
new=[]
for word in candidates:
if len(word)
max_len:
new.append(word)
new.sort()
ans+=new[0]
words.remove(new[0])
else:
break
print(ans)

33 执行时长

m=int(input())
n=int(input())
num=list(map(int, input().split()))
ans=0
overflow=0
for i in range(n):
if nums[i]+overflow>m:
overflow=nums[i]+overflow-m
else:
overflow=0
ans+=1
while overflow: # 处理最后的堆积
overflow=overflow-m
ans+=1
print(ans)

34 整型数组按个位值排序

nums=list(map(int, input().split(",")))
def func(num):
return num[-1]
nums.sort(key=func)
print(",".join(nums))

35 找终点

nums=list(map(int, input().split()))
length=len(nums)
ans=[]
for i in range(1, length//2):
step=1
index=i
while index<length-1:
index+=nums[index]
step+=1
if index==length-1:
ans.append(step)
if len(ans)>0:
ans.sort()
print(ans[0])
else:
print(-1)

36 用连续自然数之和来表达整数

t=int(input())
nums=[]
for i in range(1, t+1):
nums.append(i)
ans=[]
left=right=0
while right<t:
if sum(nums[left:right])==t:
ans.append(nums[left:right])
elif sum(nums[left:right])<t:
right+=1
elif sum(nums[left:right])>t:
left+=1
right=left
ans=sorted(ans, key=lambda x: len(x))
for i in ans:
print(str(t)+"="+"+".join(str(x) for x in ans[i]))
print("Result:"+str(len(ans)))

37 运维日志排序

def helper(nums):
nums=nums.replace(",","😊.split("😊
return int(nums[0])36001000+int(nums[1])601000+int(nums[2])*1000+int(nums[3])

n=int(input())
nums=[]
for i in range(n):
nums.append(input())
ans=sorted(nums, key=helper)
for i in ans:
print(i)

38 用户调度问题

n=int(input())
nums=[]
for _ in range(n):
nums.append(list(map(int, input().split())))
ans=0
previdx=-1
min_sum=0
for i in range(n):
for j in range(3):
if (previdx!=j and min_sum==0) or (previdx!=j and min_sum>=nums[i][j]):
min_sum=nums[i][j]
newidx=j
ans+=min_sum
previdx=newidx
print(ans)

39 最大N个数和最小N个数的和

m=int(input())
nums=list(set(input().split(" ")))
n=int(input())
nums=nums.sort()
length=len(nums)
if length/2>=n:
ans=0
for i in range(n):
ans+=int(nums[i])+int(nums[length-i-1])
else:
print(-1)
print(ans)

40 字符串加密

n=int(input())
for i in range(n):
nums.append(input()) # 多行输入
off=[0]*50
arr={'a', 'b', ....,'z'} # 列出26个字母
off[0]=1
off[1]=2
off[2]=4
for i in range(3, 50):
off[i]=off[i-1]+off[i-2]+off[i-3]
def func(nums, arr):
for i in range(n):
for j in range(len(nums[i])):
ch=nums[i][j]
offset=off[j]
ch=arr[(ch-'a'+off)%26]
ans.append(ch)
return ans
for i in range(n):
print(func(nums, arr))

41 按索引范围翻转文章片段

s=input()
start=int(input())
end=int(input())
s1=s.split(" ")
ans=s1[start: end+1]
print(ans[::-1])

42 5键键盘

s=str(input().strip())
screen=''
clip=''
selected=False
for ch in s:
if ch'1' and not selected:
screen+='a'
elif ch
'1' and selected:
screen='a'
selected=False
elif ch'2' and selected and screen:
clip=screen
elif ch
'3' and selected and screen:
clip=screen
screen=''
selected=False
elif ch'4' and selected:
screen=clip
selected=False
elif ch
'4' and not selected:
screen+=clip
elif ch=='5' and screen:
selected=True
print(len(screen))

43 报数游戏

m=int(input())
if m<=1 or m>=100:
print("ERROR!")
nums=list(range(1, 101))
ms=[]
for num in nums:
if num%m==0:
ms.append(num)
while len(nums)>=m:
prev=[]
for i in range(1, len(nums)+1):
if i>ms[0]:
nums=nums[i:]+prev
ms.remove(ms[0])
break
elif i not in ms:
prev.append(nums[i])
nums.sort()
print("".join(str(x) for x in nums))

第二种 比较好理解 但是没测试过

nums=[]
for i in range(1, 101):
nums.append(i)
i=n-1 # 初始下标
while len(nums)>=n:
nums.remove(i) # 移除报n的人
i-=1
i=i+n if i+n<len(nums) else i+n-len(nums) # 因为是圆,所以下标越界以后会绕到最前面
print(nums)

44 查找众数以及中位数

mode=[]
nums=list(map(int, input().split()))
dict={}
for num in nums:
if num not in dict:
dict[num]=1
else:
dict[num]+=1
count=max(dict.values())
for key, value in dict.items():
if value==count:
mode.append(key)
mode=sorted(mode)
if len(mode)%2!=0:
print(mode[len(mode)//2])
else:
print(0.5*(mode[len(mode)/2]+mode[len(mode)/2-1]))

45 英文输入法

import re
ipt=input().split(','|'.'|' '|'?'|"'"|"!"|"😊 # 这里没测试过
pre=input()
ans=[]
for str in ipt:
if str.startswith(pre) and str not in ans:
ans.append(str)
if len(ans)==0:
print(pre)
else:
ans.sort()
for i in range(len(ans)):
if i!=len(ans)-1:
print(ans[i]+" ")
else:
print(ans[i])

46 高矮个子排队

nums=list(map(int, input().split()))
for i in nums:
if not i.isnumeric():
print("[ ]")
for i in range(len(nums)-1):
if i%20 and nums[i]<nums[i+1]:
tmp=nums[i]
nums[i]=nums[i+1]
nums[i+1]=tmp
elif i%2
1 and nums[i]>nums[i+1]:
tmp=nums[i]
nums[i]=nums[i+1]
nums[i+1]=tmp
for i in range(len(nums)):
if i!=len(nums)-1:
print(nums[i]+" ")
else:
print(nums[i])

47 工号不够用了怎么办

x=input().split()
people=int(x[0])
alpha=int(x[1])
ans=1
while 26alpha*10ans<people:
ans+=1
print(ans)

48 靠谱的车

n=int(input())
ans=n
temp=0
k=0
j=1
while n>0:
if n%10>4: # 先判断个位上是否跳了4,如果个位上是5-9,就先temp=1
temp+=(n%10-1)k+j
else:
temp+=(n%10)
k
k=k9+j # k代表跳了多少次4,多收了多少个1元
j
=10 # j代表位数,1代表个位,10代表十位
n/=10 # 相当于将N整体右移一位
print(ans-temp)

第二种 好像不对

n=int(input())
count=0
for i in range(1, n+1):
str_i=str(i)
if '4' in str_i:
count+=1
print(n-count)

第三种

n=int(input())
ans=0
for i in range(1, len(n)+1):
n_int=int(n[-i])
if n_int>4:
n_int-=1
ans+=n_int*(9**(i-1))
print(ans)

49 分班问题

nums=list(map(int, input().split()))
ans1=[]
ans2=[]
if "Y" in nums[0]:
print("ERROR")
else:
for i in range(len(nums)):
if "Y" in nums[i]:
ans2.append(nums[i-1].split("/")[0])
ans2.append(nums[i].split("/")[0])
if len(ans2)!=0 or "N" in nums[i] or i==len(nums)-1:
ans1.append(list(set(ans2)))
ans2=[]
if len(ans1)>1:
for i in ans1:
i.sort(key=lambda x: int(x))
print("".join(i))
else:
ans1[0].sort(key=lambda x: int(x))
print("".join(ans[0]))
print("\n")

50 最大花费金额

nums=list(map(int, input().split()))
r=int(input())
ans=[]
nums.sort()
for i in range(len(nums)-2):
left=i+1
right=len(nums)-1
while left<right:
if nums[i]+nums[left]+nums[right]<=r:
ans.append(nums[i]+nums[left]+nums[right])
left+=1
else:
right-=1
ans.sort()
print(ans[-1])

51 最长连续子序列

nums=list(map(int, input().split()))
target=int(input())
total=0
for i in range(len(nums)):
total+=ans[i]
if total<target:
print(-1)
elif totaltarget:
print(len(nums))
else:
left=right=0
temp=0
while left<len(nums) and right<len(nums):
if temp<target:
temp+=nums[right]
right+=1
elif temp>target:
temp-=nums[left]
left+=1
if temp
target:
print(right-left)
break

52 字符统计及重排

s=input()
nums=[0]*1000 # 位置根据ord值,用来装字母,才设了一个很大的长度
for ch in s:
nums[ord(ch)]+=1
count=0
for num in nums:
count=max(count, num)
for i in range(count, 0, -1):
for j in range(97, 123): # 分别大小写字母的ord值范围
if nums[j]i:
print(chr(j)+":"+i+";")
for j in range(65, 91):
if nums[j]
i:
print(chr(j)+":"+i+";")

53 滑动窗口最大值

n=int(input())
nums=list(map(int, input().split()))
m=int(input())
if m==n:
print(sum(nums))
left=0
right=m
ans=0
while right<=n:
ans=max(ans, sum(nums[left: right])) # 可能超时,更新:减掉sum[0],加新一个数
left+=1
right+=1
print(ans)

54 TLV解析I

tag=input()
nums=deque(input().split())
while len(nums)>0:
curtag=nums.popleft()
len1=nums.popleft()
len2=nums.popleft()
length=int(len1+len2, 16)
curval=[]
for _ in range(length):
curval.append(nums.popleft())
if curtag==tag:
print(' '.join(curval))

55 数组去重和排序

nums=list(map(int, input().split(",")))
dict={}
for num in nums:
dict[num]=nums.count(num)
dict=sorted(dict.items(), key=lambda x: x[1], reverse=True)
ans=[]
for num in dict:
ans.append(num[0])
print(ans)

56 字符串筛选排序

s=list(input().split())
k=int(input())
s1=s.sort()
if k>len(s):
target=s1[-1]
else:
target=s1[k-1]
ans=s.find(target)
print(ans)

57 连续字母长度

s=input()
k=int(input())
idx=0
dic={}
for i in range(len(s)):
idx=i
while idx+1<len(s) and s[idx]==s[idx+1]:
idx+=1
ch=s[i]
if ch not in dic or (ch in dic and dic[ch]<idx-i+1):
dic[ch]=idx-i+1
i=idx
ans=sorted(dic.items(), key=lambda x: x[1], reverse=True)
if k-1<len(ans):
print(ans[k-1][1])
else:
print(-1)

58 停车场车辆统计

cars="".join(i for i in input().split(",")).split("0")
ans=0
for car in cars:
leneach=len(car)
if leneach0:
ans=ans
elif leneach%3
0 and leneach!=0:
ans=ans+leneach/3
elif leneach%3!=0:
ans=ans+leneach//3+1
print(ans)

59 比赛

m, n=map(int, input().split(','))
nums=[]
if not (3<=m<=10 and 3<=n<=10):
print(-1)
for i in range(m):
nums.append(list(map(int, input().split(','))))
for num in nums:
for x in num:
if x>10 or x<1:
print(-1)
ans=[]
def compare(idx1, idx2, nums):
A=[]
B=[]
for i in range(len(nums)):
for j in range(len(nums[0])):
A.append(nums[i][idx1])
B.append(nums[i][idx2])
A.sort(reverse=True)
B.sort(reverse=True)
if sum(A)>sum(B):
return idx1
elif sum(A)<sum(B):
return idx2
else:
for i in range(m):
if A[i]-B[i]>0:
return idx1
elif A[i]-B[i]<0:
return idx2
else:
continue
for i in range(3):
idx=0
for j in range(1, n):
larger=compare(idx, j, nums)
idx=larger
ans.append(idx+1)
print(','.join(ans))

60 太阳能板最大面积

nums=list(map(int, input().split(",")))
n=len(nums)
ans=0
for i in range(n-1):
for j in range(i+1, n):
leftH=nums[i]
rightH=nums[j]
length=j-i
if leftH>rightH:
if ans<rightHlength:
ans=rightH
length
else:
if ans<leftHlength:
ans=leftH
length
print(ans)

61 绘图机器

ipt=input().split()
N=int(ipt[0])
E=int(ipt[1])
ans=0
tempx=0
tempy=0
for i in range(N):
num=input().split()
x=num[0]
ans+=(x-tempx)abs(tempy)
tempy+=num[1]
tempx=x
ans+=(E-tempx)
tempy
print(ans)

第二种

[n, e]=list(map(int, input().split()))
ans=0
curx=cury=0
for i in range(n):
[x, offset]=list(map(int, input().split()))
ans+=(x-curx)abs(cury)
curx=x
cury+=offset
if curx<e:
ans+=(e-curx)
abs(cury)
print(ans)

第三种

n, e=map(int, input().split())
lst=[]
for i in range(n):
lst.append(map(int, input().split()))
ans=0
high=0
for i in range(1, len(lst)):
high+=lst[i-1][1]
ans+=abs((lst[i][0]-lst[i-1][0])high)
ans+=abs((e-lst[n-1][0])
(high+lst[n-1][1]))
print(ans)

62 最大时间

nums=list(map(int, input().split(',')))
maxh=0
maxm=0
maxs=0
for i in range(6):
for j in range(6):
if i!=j and int(str(nums[i])+str(nums[j]))<24:
maxh=max(maxh, int(str(nums[i])+str(nums[j])))
h1, h2=i, j
nums.remove(nums[h1])
nums.remove(nums[h2])
for i in range(4):
for j in range(4):
if i!=j and int(str(nums[i])+str(nums[j]))<60:
maxm=max(maxm, int(str(nums[i])+str(nums[j])))
m1, m2=i, j
nums.remove(nums[m1])
nums.remove(nums[m2])
s1=int(str(nums[0])+str(nums[1]))
s2=int(str(nums[1])+str(nums[0]))
if s1>s2:
maxs=s1
else:
maxs=s2
if maxh and maxm and maxs:
print(str(maxh)+":"+str(maxm)+":"+str(maxs))
else:
print("invalid")

63 拼接URL

x=input()
ans=x.replace(',', '/')
ans=ans.replace('//', '/')

第二种

x=input().split(',')
prefix=x[0]
surfix=x[1]
if len(prefix)0 and len(surfix)0:
print('/')
while prefix.endswith('/'):
prefix=prefix[:-1]
while surfix.startswith('/'):
surfix=surfix[1:]
print(prefix+'/'+surfix)

64 第K个排列

from itertools import permutations
n=int(input())
k=int(input())
nums=[i for i in range(1, n+1)]
results=list(permutations(nums, n))
ans=results[k-1]
print(int("".join([str(x) for x in ans])))

65 非严格递增连续数字序列

s=input()
if len(s)0:
print(0)
if len(s)
1 and s[0]>='0' and s[0]<='9':
print(1)
length=0
ans=0
for i in range(len(s)):
if s[i]>='0' and s[i]<='9':
length=1
for j in range(i+1, len(s)):
if s[j]>='0' and s[j]<='9' and s[j]>=s[i]:
length+=1
else:
break
ans=max(ans, length)
print(ans)

66 分糖果

n=int(input())
count=0
def func(n, count):
if n<=1:
return coount
if n%2==0:
return func(n/2, count+1)
return min(func(n+1, count+1), func(n-1, count+1))
print(func(n, count))

67 数字涂色

n=int(input())
nums=list(map(int, input().split()))
nums.sort()
ans=0
flag=[0]*n
for i in range(n):
if flag[i]>0:
continue
else:
for j in range(i+1, n):
if nums[j]%nums[i]==0:
flag[j]+=1
ans+=1
print(ans)

68 数组拼接

length=int(input())
n=int(input())
nums=[]
ans=[]
for i in range(n):
nums.append(list(map(int, input().split(','))))
i=0
while nums:
if len(nums[i])>n:
temp=nums[i][:n]
nums[i]=nums[i][n:]
else:
temp=nums[i]
nums.pop(i)
dp+=temp
i+=1
if i>=len(nums):
i=0
print(','.join(ans))

69 整数对最小和

nums1=list(map(int, input().split()))
nums2=list(map(int, input()).split())
k=int(input())
res=[]
ans=0
for i in range(1, len(nums1)):
for j in range(1, len(nums2)):
res.append(nums1[i]+nums2[j])
res.sort()
for i in range(k):
ans+=res[k]
print(ans)

70 相对开音节

def check(word):
def checkTrue(s):
if s[0]'a' or s[0]'e' or s[0]'i' or s[0]'o' or s[0]'u':
return False
if s[1]!='a' or s[1]!='e' or s[1]!='i' or s[1]!='o' or s[1]!='u':
return False
if s[2]
'a' or s[2]'e' or s[2]'i' or s[2]'o' or s[2]'u' or s[2]=='r':
return False
if s[3]!='e':
return False
return True

ans=0
word_r=""
for i in range(len(word)-1, -1):
    word_r.append(word[i])
if len(word_r)>=4:
    left=0
    right=4
    while right<=len(word_r):
        if checkTrue(word_r[left: right]):
            ans+=1
        left+=1
        right+=1
return ans

s=input().split()
ans=0
for word in s:
for ch in word:
if not ch.isalpha():
break
ans+=check(word)
print(ans)

71 喊7的次数重排

nums=list(map(int, input().split()))
n=len(nums)
total=0
for num in nums:
total+=num # 总共有多少次7
ans=[0]*n
idx=1
count=0
while count<total:
if idx%7==0 or '7' in str(idx):
i=(idx%n)-1
ans[i]+=1
total-=1
else:
idx+=1
print(" ".join(ans))

72 计算礼品发放的最小分组数目

total=int(input())
nums=list(map(int, input().split()))
nums=nums.sort()
ans=0
i=0
j=len(nums)-1
while j>=i:
if i==j:
ans+=1
break
if nums[i]+nums[j]<=total:
ans+=1
i+=1
j-=1
else:
ans+=1
j-=1
print(ans)

73 勾股数元组

n=int(input())
m=int(input())
ans=[]
flag=0
for a in range(n, m+1):
for b in range(a+1, m+1):
for c in range(b+1, m+1):
if helper(a, b, c)0 and a2+b2c**2:
ans.append([a, b, c])
flag=1
if flag==0:
print("NA")
else:
for i in range(len(ans)):
print(ans[i][0]+" "+ans[i][1]+" "+ans[i][2]+"\n")

def helper(a, b, c):
flag=0
if helper2(a, b)1 or helper2(b, c)1 or helper2(a, c)1:
flag=1
return flag
def helper2(num1, num2):
flag=0
for i in range(2, min(num1, num2)+1):
if num1%i
0 and num2%i==0:
flag=1
break
return flag

74 火星文计算

s=input()
def helper(s):
s_r=s[::-1]
idx_r=s_r.find("#")
idx=len(s)-idx_r-1
if idx!=-1:
left=s[:idx]
right=s[idx+1:]
return 2helper(left)+3helper(right)+4
idx_r=s_r.find("$")
idx=len(s)-idx_r-1
if idx!=-1:
left=s[:idx]
right=s[idx+1:]
return 3*helper(left)+helper(right)+2
return int(s)
print(helper(s))

75 猴子爬山

n=int(input())
def func(n):
if n1 or n2:
return 1
elif n==3:
return 2
else:
return func(n-3)+func(n-1)
print(func(n))

76 最远足迹

s=input()
ans="(0,0)"
dis=0
left=[]
right=[]
for i in range(len(s)):
if s[i]"(":
left.append(i)
if s[i]
")":
right.append(i)
for i in range(len(left)):
temp=s[left[i]+1, right[i]].split(",")
if temp[0]!='0' and temp[1]!='0':
x=int(temp[0]) # 注意整型和字符的区别,运算要用整型,打印结果要用字符
y=int(temp[1])
if 0<x<1000 and 0<y<1000 and xx+yy>dis:
dis=xx+yy
ans="("+temp[0]+","+temp[1]+")"
print(ans)

77 字符串序列判定

S=input()
L=input()
i=0
j=0
while i<len(S) and j<len(L):
if S[i]L[j]:
i+=1
j+=1
if i
len(S):
print(L.find(S[-1]))
else:
print(-1)

78 按身高和体重排队

n=int(input())
heights=list(map(int, input().split()))
weights=list(map(int, input().split()))
nums=[]
for i in range(n):
nums.append([heights[i], weights[i], i+1])
def check(nums): # 对于单个数据来说
return nums[0], nums[1]
ans=sorted(nums, key=check) # 或许也可以: key=lambda x: (x[0], x[1]),降序前面加个负号
for i in ans:
print(" ".join(str(i[2])))

79 找车位

nums=list(map(int, input().split()))
ans=0
def func(nums, idx):
left=right=0
for i in range(idx):
if nums[i]1:
left=i
for i in range(idx, len(nums)):
if nums[i]
1:
right=i
break
return min(idx-left, right-idx) # 注意这里是min

for i in range(len(nums)):
if nums[i]==1:
continue
ans=max(ans, func(nums, i))
print(ans)

80 最长元音子串的长度

s=input()
ans=''
for i in range(len(s)-1):
if s[i] not in 'aeiouAEIOU':
continue
for j in range(i+1, len(s)):
if s[j] in 'aeiouAEIOU':
if len(s[i:j+1])>len(ans):
ans=s[i:j+1]
else:
break
print(len(ans))

81 磁盘容量排序

n=int(input())
nums=[]
for i in range(n):
nums.append(input())
ans=[]
cursum=0
total=0
for num in nums:
for ch in num:
if ch.isdigit():
cursum=cursum10+(cursum-'0')
else:
if ch"M":
total+=cursum
elif ch
"G":
total+=cursum
1024
elif ch=="T":
total+=cursum10241024
ans.append([total, num])
nums_sorted=sorted(ans, key=lambda x: x[0])
for i in nums_sorted:
print(i[1])

82 乱序整数序列两数之和绝对值最小

nums=list(map(int, input().split()))
nums.sort()
total=-1
ans=[]
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
sum=abs(nums[i]+nums[j])
if total==-1 or sum<total:
total=sum
ans.append(i)
ans.append(j)
ans.append(total)
if ans[0]>ans[1]:
print(str(ans[1])+" "+str(ans[0])+" "+str(ans[2]))
else:
print(" ".join(str(num) for num in ans))

83 考勤信息

def award(s):
if s.count('absent')>1: # 字符串中某字符的个数,或列表中某元素的个数
return 'false'
if s.count('late late')>0 or s.count('leaveearly leaveearly')>0 or s.count('late leaveearly') or s.count('leaveearly late'):
return 'false'
s1=s.split(" ")
for i in range(len(s1)):
if s1[i]'absent' or s1[i]'late' or s1[i]=='leaveearly':
num=0
l=s1[i+1: i+7]
num+=l.count('absent')
num+=l.count('late')
num+=l.count('leaveearly')
if num>2:
return 'false'
return 'true'

n=int(input())
ans=[]
for i in range(n):
ipt=input().strip()
ans.append(award(ipt))
print(" ".join(ans))

84 快递运输

nums=list(map(int, input().split(",")))
n=int(input())
ans=0
nums=nums.sort()
for i in range(len(nums)):
total+=nums[i]
if total<=n:
ans+=1
print(ans)

85 计算最大乘积

s=input().split(",")
ans=0
def helper(str1, str2):
str1.sort()
str2.sort()
idx1=idx2=0
while idx1<len(str1) and idx2<len(str2):
if str1[idx1]==str2[idx2]:
return True
elif str1[idx1]<str2[idx2]:
idx1+=1
else:
idx2+=1
return False
for i in range(len(s)):
for j in range(i+1, len(s)):
if not helper(s[i], s[j]):
ans=max(ans, len(s[i])*len(s[j]))
print(ans)

86 求符合要求的结对方式

n=int(input())
nums=list(map(int, input().split()))
target=int(input())
ans=0
for i in range(n):
a=nums[i]
for j in range(i+1, n):
b=nums[j]
if a+b==target:
ans+=1
print(ans)

87 数列描述

n=int(input())
prev="1"
for i in range(n-1): # 或许这里的边界要改一下?
cur=""
pos=0
start=0
while pos<len(prev):
while pos<len(prev) and prev[pos]==prev[start]:
pos+=1
cur+=str(pos-start)+prev[start]
start=pos
prev=cur
print(prev)

88 玩牌高手

nums=list(map(int, input().split(",")))
ans=[]
prev=0
for i in range(len(nums)):
if i<3:
if nums[i]<=0:
ans[i]=0
else:
ans[i]=prev+nums[i]
else:
if nums[i]>0:
ans[i]=prev+nums[i]
else:
ans[i]=max(prev+nums[i], ans[i-3])
prev=ans[i]
print(ans[-1])

89 关联子串

s1, s2=map(str, input().split())
def permute(nums):
def backtrack(first):
if first==len(nums):
ans.append(nums[:])
for i in range(first, len(nums)):
nums[first], nums[i]=nums[i], nums[first]
backtrack(first+1)
nums[first], nums[i]=nums[i], nums[first]
ans=[]
backtrack(0)
return ans
s1_all=permute(s1)
for word in s1_all:
if word in s2:
print(s2.find(word[0]))
print(-1)

90 全排列

s=input()
def permute(s):
if len(s)0:
return []
n=len(s)
ans=[]
used=[0]*n
def backtrack(s, used, path):
if len(path)
n:
ans.append(path[:])
return
for i in range(n):
if not used[i]:
if i>0 and s[i]==s[i-1] and not used[i-1]:
continue
used[i]=1
path.append(s[i])
backtrack(s, used, path)
path.pop()
used[i]=0
backtrack(sorted(s), used, [])
return ans
ans=permute(s)
print(len(ans))

91 组成最大数

nums=input().split(",")
n=len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i]+nums[j]<nums[j]+nums[i]:
temp=nums[i]
nums[i]=nums[j]
nums[j]=temp
ans=str(int("".join(nums)))
print(ans)

92 检查是否存在满足条件的数字组合

n=int(input())
nums=list(map(int, input().split()))
nums.sort()
for i in range(n-2):
for j in range(i+1, n-1):
sum=nums[i]+2*nums[j]
if sum>nums[-1]:
break
for k in range(j+1, n):
if nums[k]==sum:
print(str(i)+" "+str(j)+" "+str(k))
break
break
break
print(0)

93 素数之积

def func(num):
for i in range(2, int(num**0.5)+1):
if num%i0:
return False
return True
num=int(input())
for i in range(2, num//2):
c=num//i
if c>=i and c*i
num and func(c) and func(i):
print(str(c)+" "+str(i))
print("-1 -1")

第二种

def check(nums):
for i in range(2, int(nums**0.5)+1):
if nums%i0:
return False
return True
n=int(input())
ans=[]
for i in range(2, n+1):
if check(i):
ans.append(i)
result=[]
for num in ans:
while n%num
0:
n//=num
result.append(num)
if n>1:
result.append(n)
print(' '.join(str(num) for num in result))

94 寻找相同子串

t=input()
p=input()
for i in range(len(t)):
if t[i]p[0] and t[i: i+len(p)]p:
print(t.find(p[0])+1)
print("No")

95 字符串变换最小字符串

s=input()
idx=0
for i in range(len(s)):
if s[i]<s[idx]:
s[idx]=s[i]
idx=i
if idx==0:
print(s)
else:
temp=s[0]
s[0]=s[idx]
s[idx]=temp
print(s)

96 找出经过特定点的路径长度

s=input()
path=input()
ans=0
start=s.find(path[0])
for i in range(len(path)-1):
end=s.find(path[i+1])
dist=abs(end-start)
start=end
ans+=dist
print(ans)

97 ABR车路径协同场景

s=input()
a=s.find('A')
b=s.find('B')
r=s.find('R')
A=[]
B=[]
R=0
for i in s[a:b]:
if i.isdigit():
A.append(i)
for i in s[b:r]:
if i.isdigit():
B.append(i)
for j in s[r:]:
if i.isdigit():
R=i
flag=False
ans=[]
for i in range(len(A)):
for j in range(i, len(B)):
if j-i<=R:
ans.append("("+i+","+j+")")
flag=True
continue
if flag==False:
ans.append("("+i+","+j+")")
else:
break
print("".join(str(x) for x in ans))

98 矩形相交的面积

s1=list(map(int, input().split()))
s2=list(map(int, input().split()))
s3=list(map(int, input().split()))
top=min(s1[1], min(s2[1], s3[1]))
bottom=max(s1[1]-s1[3], max(s2[1]-s2[3], s3[1]-s3[3]))
left=max(s1[0], max(s2[0], s3[0]))
right=min(s1[0]+s1[2], min(s2[0]+s2[2], s3[0]+s3[2]))
ans=(top-bottom)*(right-left)
print(ans)

99 We Are A Team

n, m=map(int, input().split())
if n<1 or n>=100000 or m<1 or m>=100000:
print("Null")
break
seen=set()
def check(a, b, seen):
return (a in seen) and (b in seen)
for i in range(m):
a, b, c=map(int, input().split())
if a<1 or b<1 or a>n or b>n or (c!=0 and c!=1):
print("da pian zi")
else:
if c==0:
seen.add(a)
seen.add(b)
else:
if check(a, b, seen):
print("we are a team")
else:
print("we are not a team")

100 正方形数量

n=int(input())
nums=[]
for i in range(n):
nums.append(list(map(int, input().split())))
ans=0
def check(a, b, c, d):
four=[]
four.append(a)
four.append(b)
four.append(c)
four.append(d)
sequence=[]
for i in range(4):
for j in range(i+1, n):
for k in range(j+1, n):
for l in range(k+1:n):
sequence.append(four[i], four[j], four[k], four[l])
for arr in sequence:
ac = (arr[2][0] - arr[0][0], arr[2][1] - arr[0][1])
bd = (arr[3][0] - arr[1][0], arr[3][1] - arr[1][1])
ab = (arr[1][0] - arr[0][0], arr[1][1] - arr[0][1])
bc = (arr[2][0] - arr[1][0], arr[2][1] - arr[1][1])
dc = (arr[2][0] - arr[3][0], arr[2][1] - arr[3][1])
ad = (arr[3][0] - arr[0][0], arr[3][1] - arr[0][1])
if ac[0] * bd[0] + ac[1] * bd[1] == 0 and ab[0] * bc[0] + ab[1] * bc[1] == 0 and
bc[0] * dc[0] + bc[1] * dc[1] == 0 and dc[0] * ad[0] + dc[1] * ad[1] == 0 and
ad[0] * ab[0] + ad[1] * ab[1] == 0:
return True
if n>3:
for i in range(n-3):
for j in range(i+1,n-2):
for k in range(j+1, n-1):
for l in range(k+1, n):
if check(nums[i],nums[j], nums[k], nums[l]):
ans+=1
print(ans)

101 最少交换次数

nums=list(map(int, input().split()))
k=int(input())
total=0
for num in nums:
if num<k:
total+=1
ans=total # 总共有多少个符合<k的数
for start in range(len(nums)-total+1):
window=nums[start: start+total]
got_in_this_window=0
for end in window:
if end<k:
got_in_this_window+=1
ans=min(ans, total-got_in_this_window)
print(ans)

102 解密犯罪时间

s=input()
nums=[int(i) for i in s if i!=':']
h,m=[int(i) for i in s.split('😂]
combi=[]
for i in nums:
for j in nums:
combi.append(str[i]+str[j])
ans1=[] #只动分的结果
ans2=[] #需要动小时才行
for i in range(len(combi)):
if m<int(combi[i])<=59:
ans1.append(combi[i])
if len(ans1)>0:
ans1.sort()
if h<10:
print('0'+str(h)+':'+ans1[0])
else:
print(str(h)+':'+ans1[0])
else: # 只动分无法输出结果
for i in range(len(combi)):
if h<int(combi[i])<24:
ans2.append(combi[i])
if len(ans2)>0:
ans2.sort()
print(str(ans2[0])+':'+str(min(combi)))
else:
print(str(min(combi))+':'+str(min(combi))) #当天无结果,输出第二天的最小时间

103 水仙花数II

s=input()
nums=[ord(ch) for ch in s]
def backtrack(nums, path, ans):
def check(n):
if n<100 or n>999:
return False
n_l=map(int, str(n))
sum=0
for i in range(3):
sum+=n_l[i]**3
if sumn:
return True
return False
if not nums:
ans.append(path[:])
return
for i in range(1, len(nums)+1):
if check(sum(nums[:i])):
path.append(nums[:i])
backtrack(nums[i:], path, ans)
path.pop()
path, ans=[],[]
backtrack(nums, path, ans)
if len(ans)
0:
print(0)
elif len(ans)>1:
print(-1)
else:
print(len(ans[0]))

104 水仙花数I

def check(num, n):
ans=False
sum=0
num=map(int, str(num)) # 整数变List,才能遍历
for i in range(n):
sum+=num[i]n
if sum==num:
ans=True
return ans
n=int(input())
m=int(input())
ans=[]
if n<3 or n>7:
print(-1)
min=10
(n-1)
max=10**n-1
for i in range(min, max+1):
if check(i, n):
ans.append(i)
if m>len(ans)-1:
print(ans[-1]*m)
else:
print(ans[m])

105 补种未成活胡杨

n=int(input())
m=int(input())
ms=list(map(int, input().split()))
k=int(input())
nums=[1]*n
for i in range(n):
if i+1 in ms:
nums[i]=0
ans=0
i=0
j=k
while k<len(nums):
count=nums[i:j].count(0)
if count<k:
j+=1
elif count==k:
ans=max(ans, j-i)
j+=1
else:
i+=1
print(ans)

106 字符串排序

s=list(input().split())
seen=set()
for i in range(s):
if i>0 and s[i].upper() in seen:
s.remove(s[i])
seen.add(s[i])
s=sorted(s, key=lambda x: ord(x), len(x))
for word in s:
print(" ".join(word))

107 全量和已占用字符集

s=input().split("@")
if len(s)<2:
print(s[0])
letters=[]
dict={}
full=s[0].split(",")
for each in full:
eg=each.split("😊
letters.append(eg[0])
dict[eg[0]]=eg[1]
used=s[1].split(",")
for each in used:
eg=each.split("😊
full=dict[eg[0]]
if full>eg[1]:
dict[eg[0]]=full-eg[1]
else:
dict.remove(eg[0])
letters.remove(eg[0])
ans=""
for ch in letters:
count=dict[ch]
ans.append(ch+":"+str(count)+",")
ans.remove[-1]
print(ans)

108 密钥格式化

s=input()
k=int(input())
idx=s.find("-")
start=s[:idx]
rest=s[idx:]
ipt=""
for ch in rest:
if ch=="-":
continue
elif ch.isdigit():
ipt+=str(ch)
else:
ipt+=ch.upper()
if len(ipt)<k:
print(start+"-"+ipt)
n=len(ipt)
ans=[]
for i in range(0, n, k):
ans.append(ipt[i])
print(start+"-"+"-".join(str(x) for x in ans))

109 数字字符串组合倒序

有点细节上的问题需要改,关于-的

def helper(temp, ans):
if temp:
if '--' in temp:
ans+=temp.split('--')
elif temp[-1]'-':
ans+=temp[-1]
else:
ans.append(temp)
s=input()
temp=""
for ch in s:
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9' or (ch
'-' and temp):
temp+=ch
else:
helper(temp, ans)
temp=""
print(helper(temp, ans)[::-1])

110 查找接口成功率最优时间段

def helper(minAverageLost, nums):
ans=[]
for i in range(len(nums)):
for j in range(i+1, len(nums)):
window=nums[i:j]
total=0
for num in window:
total+=num
temp=""
if total<=(i-j+1)*minAverageLost:
temp=i+"-"+j
ans.append(temp)
minAverageLost=int(input())
nums=list(map(int, input().split()))
helper(minAverageLost, nums)
if len(ans)>0:
for i in range(len(ans)):
print(" ".join(ans[i]))

111 在字符串中找出连续最长的数字串(含“+-”号)

s=input()
temp=[]
flagpoint=False
flagsignal=False
for i in len(s):
if s[i].isdigit():
temp.append(s[i])
elif s[i]'.' and s[i-1].isdigit() and s[i+1].isdigit() and flagpointFalse:
temp.append(s[i])
elif s[i] in '+-' and len(temp)0 and flagsignalFalse:
temp.append(s[i])
else:
ans.append(temp)
flagpoint=False
flagsignal=False
temp=[]
continue
max_temp=""
for temp in ans:
if len(max_temp)<=len(temp):
max_temp=temp
print(" " if not max_temp else max_temp)

112 数组连续和

n, x=input().split()[0], input().split()[1]
nums=list(map(input().split()))
ans=[]
def backtrack(ans, temp, nums, total, x, start, visited):
if start>len(nums):
return
if total>=x:
ans.append(temp[:])
for i in range(start, len(nums)):
if visited[i]:
continue
if i>1 and visited[i-1]==False and visited[i-2]:
return
visited[i]=True
total+=nums[i]
temp.append(nums[i])
backtrack(ans, temp, nums, total, x, i+1, visited)
visited[i]=False
total-=nums[i]
temp.remove(temp[-1])
backtrack(ans, [], nums, 0, x, 0, False)
print(len(ans))

113 IPV4地址转换成整数

nums=list(map(int, input().split("#")))
if len(nums)!=4:
print("invalid IP")
ans=0
if not (nums[0]>=1 and nums[0]<=128):
print("invalid IP")
for i in range(1, 4):
if not (nums[i]>=0 and nums[i]<=255):
print("invalid IP")
for i in nums:
ans=ans<<8|int(i)
print(ans)

114 敏感字段加密

k=int(input())
s=input()
clear=[]
for i in range(len(s), ):
if s[i]'"':
j=i+1
for j in range(len(s)):
if s[j]
'"':
break
clear.append(s[i:j+1])
i=j+1
continue
elif s[i]'_':
j=i+1
for j in range(len(s)):
if s[j]
'':
break
clear.append(s[i, j])
i=j
continue
else:
i+=1
continue
ans=""
if k>=len(clear):
print("ERROR")
elif k==len(clear)-1:
for i in range(len(clear)-1):
ans.append(clear[i]).append("
")
ans.append("")
elif k<len(clear)-1:
for i in range(len(clear)-1):
if i==k:
ans.append("
").append("")
else:
ans.append(clear[i]).append("
")
ans.append(clear[-1])
print(ans)

115 路灯照明问题

n=int(input())
nums=list(map(int, input().split()))
intervals=[]
ans=[]
covered_length=0
for i in range(n):
if i!=0:
left=i100-nums[i]
else:
left=0
if i!=n-1:
right=i
100+nums[i]
else:
right=(n-1)100
intervals.append([left, right])
intervals.sort(key=lambda x: x[0])
for interval in intervals: # 这一段和力扣的合并区间那道题类似
if not ans or ans[-1][1]<interval[0]:
ans.append(interval)
else:
ans[-1][1]=max(ans[-1][1], interval[1])
for i in ans:
covered_length+=i[1]-i[0]
print((n-1)
100-covered_length)

116 数大雁

s=input() # 这种方法不确定全对
ans=0
dic={'q':0, 'u':0, 'a':0, 'c':0, 'k':0}
for i in range(len(s)):
dic[s[i]]+=1
if not dic['q']>=dic['u']>=dic['a']>=dic['c']>=dic['k']:
print(-1)
if all (val>0 for val in list(dic.values())):
for ch in 'quack':
dic[ch]-=1
else:
ans=max(ans, dic['q'])
print(ans)

第二种

chars=input()
dp=[]
def dfs(nums):
# 确定一个有效的叫声范围,从q开始,到k结束,且中间顺序包含uac
s=0
e=0
for c in 'uack':
e+=nums[e:].index(c)
e+=1
dct={'q':0, 'u':0, 'a':0, 'c':0, 'k':0}
k=0
while k<len(nums):
if nums[k]=='q': # q只有在范围内的q是有效的
if s<=k<=e:
dict['q']+=1
else:
dct[nums[k]]+=1
k+=1
dp.append(min(dct.values()))
i=0
while 'q' in chars[i:]:
i=chars.index('q')
dfs(chars[i:])
chars=chars[i+1:]
print(max(dp))

从这里开始往后,或许不是100分的题,只是因为他们是新题,把它更新到这里了。或许有些题解复杂的就是200分的

117 路灯照明

n, l=map(int, input().split())
nums=list(map(int, input().split()))
nums.sort()
ans=max(nums[0], l-nums[n-1])
for i in range(n-1):
cur=(nums[i+1]-nums[i])/2
ans=max(ans, cur)
print(round(ans, 2))

118 跳格子

n=int(input())
nums=[]
for i in range(n):
x=input().split()
if x and len(x)2:
nums.append(tuple(map(int, x))) # 这里的tuple或许可以改一下?
else:
break
nums=sorted(nums, key=lambda x: x[0])
state=[1]*n
for start, end in nums:
state[end]=0
if max(state)
0:
print('no')
continue
dp=[0]
def dfs(s, link):
if len(link)len(nums) and sorted(link, key=lambda x: x[0])nums:
dp.append(1)
return
ends=[]
for start_, end_ in nums:
if sstart_:
link.append((start_, end_))
ends.append(end_)
for end_ in ends:
dfs(end_, link)
for i in range(n):
if state[i]
1:
dfs(i, [])
if max(dp):
print('yes')
else:
print('no')

第二种

while True:
try:
n=int(input())
flag=True
nums=[]
key=input().split()[0]
if key==-1:
break
if key<1 or key>n:
print(-1)
value=input().split()[1]
if value<1 or value>n:
print(-1)
listchild=[]
listchild.append(key)
listchild.append(value)
nums.append(listchild)

    def check(nums):
        for temp in nums:
            if temp[0]==nums[len(nums)-1]:
                if temp[1] in nums:
                    return True
                nums.append(temp[1])
                check(nums)
        return False
    
    for i in range(len(nums)):
        if check(nums[i]):
            flag=False
            break
    if flag:
        print('yes')
    else:
        print('no')

119 二叉树中序遍历

class Node:
def init(self, val):
self.val=val
self.left=None
self.right=None
def get_node(c):
if type(c)Node:
return c
elif c:
return Node(c)
else:
return None
def get_root(stack):
j=len(stack)-1
while j>=0:
if stack[j]
'{':
break
j-=1
if stack[j:][1]',':
left_=None
else:
left_=get_node(stack[j:][1])
if stack[j:][-1]
',' or ',' not in stack[j:]:
right_=None
else:
right_=get_node(stacl[j:][-1])
stack=stack[:j]
root_=get_node(stack.pop(-1))
root_.left=left_
root_.right=right_
stack.append(root_)
return stack
while True:
try:
chars=input().replace(' ', '')
stack=[]
for c in chars:
if c=='}':
stack=get_root(stack)
else:
stack.append(c)
dp=[]
def dfs(root):
if not root:
return
dfs(root.left)
dp.append(root.val)
dfs(root.right)
dfs(stack[0])
print(''.join(dp))
except:
break

120 事件推送

m, n, r=map(int, input().split())
A=list(map(int, input().split()))
B=list(map(int, input().split()))
for a in A:
for b in B:
if a<=b and b-a<=r:
print(a+" "+b)
break

121 出错的或电路

n=int(input())
s1=input()
s2=input()
nums=[]
one=0
zero=0
for i in range(n):
if s1[i]'0':
zero+=1
if s2[i]
'0':
nums.append(1)
else:
one+=1
if s2[i]'0':
nums.append(0)
ans=0
for num in nums:
if num
0:
ans+=zero
else:
ans+=one
print(ans)

122 图像物体的边界

row, col=map(int, input().split())
nums=[]
for i in range(row):
nums.append(list(map(int, input().split())))
for i in range(row):
for j in range(col):
if nums[i][j]5:
if i>0:
if nums[i-1][j]
1:
nums[i-1][j]=2
if j>0:
if nums[i-1][j-1]1:
nums[i-1][j-1]=2
if j<col-1:
if nums[i-1][j+1]
1:
nums[i-1][j+1]=2
if j>0:
if nums[i][j-1]1:
nums[i][j-1]=2
if i<row-1:
if nums[i+1][j]
1:
nums[i+1][j]=2
if j>0:
if nums[i+1][j-1]1:
nums[i+1][j-1]=2
if j<col-1:
if nums[i+1][j+1]
1:
nums[i+1][j+1]=2
if j<col-1:
if nums[i][j+1]1:
nums[i][j+1]=2
def helper(i, j):
if i>0:
if nums[i-1][j]
2:
nums[i-1][j]=0
helper(i-1, j)
if j>0:
if nums[i-1][j-1]2:
nums[i-1][j-1]=0
helper(i-1, j-1)
if j<col-1:
if nums[i-1][j+1]
2:
nums[i-1][j+1]=0
helper(i-1, j+1)
if j>0:
if nums[i][j-1]2:
nums[i][j-1]=0
helper(i, j-1)
if i<row-1:
if nums[i+1][j]
2:
nums[i+1][j]=0
helper(i+1, j)
if j>0:
if nums[i+1][j-1]2:
nums[i+1][j-1]=0
helper(i+1, j-1)
if j<col-1:
if nums[i+1][j+1]
2:
nums[i+1][j+1]=0
helper(i+1, j+1)
if j<col-1:
if nums[i][j+1]2:
nums[i][j+1]
0
helper(i, j+1)
count=0
for i in range(row):
for j in range(col):
if nums[i][j]==2:
count+=1
nums[i][j]=0
helper(i, j)
print(count)

print()

123 二叉树层序遍历

124 移除K位数字

num=input()
k=int(input())
stack=[]
for i in num:
while stack and k and stack[-1]>i:
k-=1
stack.pop()
stack.append(i)
print(''.join(stack[:len(stack)-k].lstrip('0')) or '0')

125 字符串子序列II

a=input()
b=input()
j=len(b)-1
flag=True
for i in range(len(a)-1, -1, -1):
if j-1:
print(-1)
exit(0) # 退出程序 或许可以用break?
find=False
for k in range(j, -1, -1):
if a[i]
b[k]:
j=k-1
find=True
break
if not find:
flag=False
if not flag:
print(-1)
else:
print(j+1)

126 分苹果

n=int(input())
a=list(map(int, input().split()))
ans=0
for x in a:
ans=ans^x # 异或:不进位
if ans!=0:
print(-1)
else:
print(sum(a)-min(a))

127 找单词

n=int(input())
grids=[]
for i in range(n):
grids.append(list(input().split(',')))
word=input()
wordlen=len(word)
ans=''
first=word[0]
flag=False
def nextNum(idx, row, col, temp):
if idxwordlen:
return 1
idx+=1
s=word[idx]
if row>0 and temp[row-1][col]
s:
temp[row-1][col]=''
ans+=','+(row-1)+','+col
if nextNum(idx, row-1, col, temp)1:
return 1
else:
ans=ans[0:len(ans)-4] # 如果失败则进行还原
temp[row-1][col]=s
if col>0 and temp[row][col-1]
s:
temp[row][col-1]=''
ans+=','+row+','+(col-1)
if nextNum(idx, row, col-1, temp)1:
return 1
else:
ans=ans[0:len(ans)-4]
temp[row][col-1]=s
if row<n-1 and temp[row+1][col]
s:
temp[row+1][col]=''
ans+=','+(row+1)+','+col
if nextNum(idx, row+1, col, temp)1:
return 1
else:
ans=ans[0:len(ans)-4]
temp[row+1][col]=s
if col<n-1 and temp[row][col+1]
s:
temp[row][col+1]=''
ans+=','+row+','+(col+1)
if nextNum(idx, row, col+1, temp)1:
return 1
else:
ans=ans[0:len(ans)-4]
temp[row][col+1]=s
return 0
for i in range(n):
for j in range(n):
if grids[i][j]
first:
temp=copy.deepcopy(grids)
ans=i+','+j
temp[i][j]=''
if nextNum(0, i, j, temp)==1:
flag=True
print(ans)
break
if flag:
break
if not flag:
print('N')

128 热点网站统计

dict={} # 用来记录数组中相同元素的个数
while True:
try:
s=input()
if not s.isdigit():
if s not in dict:
dict[s]=1
else:
dict[s]+=1
else:
n=int(input())
temp=list(dict.items())
temp=sorted(temp, key=lambda x: x[1], reverse=True)
for i in range(1, len(temp)):
if temp[i][1]==temp[i-1][1] and temp[i][0]<temp[i-1][0]:
temp[i], temp[i-1]=temp[i-1], temp[i]
ans=[]
for i in range(n):
ans.append(temp[i][0])
print(','.join(ans))

200分题

1 矩阵扩散

和腐烂的橘子很像,也和污水题很像

m1, n1=int(input().split()[0]), int(input().split()[1])
nums=[[0]n1 for _ in range(m1)]
x1=int(input().split()[2])
y1=int(input().split()[3])
x2=int(input().split()[4])
y2=int(input().split()[5])
nums[x1][y1]=1
nums[x2][y2]=1
def helper(nums):
time=0
def checkhaszero(nums):
for i in range(m1):
for j in range(n1):
if nums[i][j]==0:
return True
return False
while checkhaszero(nums):
temp=[[0]
n1 for _ in range(m1)]
for i in range(m1):
for j in range(n1):
if nums[i][j]==1:
temp[i][j]=1
if i-1>=0:
temp[i-1][j]=1
if i+1<m1:
temp[i+1][j]=1
if j-1>=0:
temp[i][j-1]=1
if j+1<n1:
temp[i][j+1]=1
nums=temp
time+=1
return time
print(helper(nums))

2 导师请吃火锅

n, m=input().split()[0], input().split()[1]
x, y=[], []
for i in range(n):
x[i]=input().split()[0]
y[i]=input().split()[1]
time=[0]n
for i in range(n):
time[i]=x[i]+y[i]
time.sort()
count=[0]
n # 记录每个时刻捞还是不捞
idx=0
count[0]=1 # 这个好像无关紧要,因为0时刻是不可能有菜好的
for i in range(1, n):
if time[i]>=time[idx]+m: # 如果菜多,就捞,用1表示
count[i]=1
idx=i
ans=0
for i in range(n):
if count[i]>0: # 陆续多次的捞,总共能吃len(count)次,每次1个菜,所以是+=1
ans+=1
print(ans)

第二种

n, m=list(map(int, input().split()))
idx=[]
for _ in range(n):
i, v=list(map(int, input().split()))
idx.append(i+v)
nums=[0]*(max(idx)+1)
for i in idx:
nums[i]=1
dp=[]
def dfs(t, data): # t可以夹菜的时间,因为每秒夹一次,也可作为时间轴
if t>=len(nums):
dp.append(sum(data))
return
if nums[t]==1: # 等于1 此时有菜 但是可以选择吃或不吃,可能会影响后面夹菜的顺序
dfs(t+m, data=[1]) # 1表示吃,吃了要直接跳到m秒后; 没吃,过1秒继续选择 吃或不吃
dfs(t+1, data)
else:
dfs(t+1, data)
dfs(1, [])
print(max(dp))

3 竖直四子棋

输出哪一步(idx+1)+结果

主要是要弄清楚横纵轴是怎么安排的,好像和平时的是相反的

m, n=input().split()[0], input().split()[1]
strings=input().split() # 列, 从1开始,先红后蓝
ints=[[0]*m for _in range(n)]
isover=False
def helper(ints, x, y):
h=len(ints)
l=len(ints[0])
count=0
base=3 # 四个棋子只要统计三次
if x<h-3:
a=x
b=y
while base!=0 and ints[a][b]ints[a+=1][b]: # 纵向
count+=1
base-=1
if count
3:
return True
count=0
base=3
if y>=3:
a=x
b=y
while base!=0 and ints[a][b]ints[a][b-=1]: # 左
count+=1
base-=1
if count
3:
return True
count=0
base=3
if y<l-3:
a=x
b=y
while base!=0 and ints[a][b]ints[a][b+=1]: # 右
count+=1
base-=1
if count
3:
return True
count=0
base=3
if x=3:
a=x
b=y
while base!=0 and ints[a][b]ints[a+=1][b-=1]: # 斜
count+=1
base-=1
if count
3:
return True
if x<h-3 and y<l-3:
a=x
b=y
while base!=0 and ints[a][b]ints[a+=1][b+=1]:
count+=1
base-=1
if count
3:
return True
return False

for i in range(len(strings)):
idx=-1
color=1 # 红
num=int(strings[i])
if num<=0 or num>m or ints[0][num-1]!=0: # 超范围或列满了
isover=True
print(i+1+',error')
break
if i%20:
color=2 # 蓝
for j in range(n-1, -1, -1):
if ints[j][num-1]
0:
idx=j
ints[j][num-1]=color # 此时棋子纵坐标为j,横坐标为num-1
break
if idx-1:
print(i+1+',error')
isover=True
break
if i>=6 and helper(ints, idx, num-1): # 有一种可以连成4个了
if color
1:
print(i+1+',red')
isover=True
break
else:
print(i+1+',blue')
isover=True
break
if not isover:
print('0, draw')

4 字符串比较

A=input()
B=input()
V=int(input())
ans=[] # 可能有多个子串,那就要求最长的子串的长度
for start in range(len(A)):
target=abs(ord(A[start])-ord(B[start]))
if target>V:
ans.append(0)
elif target==V:
ans.append(1)
else:
for end in range(start+1, len(A)):
target=target+abs(ord(A[end])-ord(B[end]))
if target<=V:
ans.append(end-start+1)
else:
break
print(max(ans))

5 找到比自己强的人数

先把数据形成数组,2列,x行

u_map的位置默认对应每个人的编号,值默认为比自己强的人数 ?

这个答案好像不是完全正确,大概是这个意思

u_map=[]
for i in range(len(matrix)):
teacher=matrix[i][0]
for j in range(len(matrix)):
student=matrix[j][1]
if teacher>student:
u_map[teacher]+=1
u_map[student]+=0
u_map.sort()
ans=[]
for i in range(len(u_map)):
ans.append(u_map[i])
ans.sort()
print('['+','.join(ans)+']')

6 机器人走迷宫

m, n=map(int, input().split())
k=int(input())
nums=[] # 0未踩过的,1是墙,2是踩过的
nums=[[0]*n for _ in range(m)]
for i in range(k): # 墙的位置设置到矩阵中
x, y=map(int, input().split())
nums[x][y]=1
def helper(nums, x1, y1, x2, y2):
if nums[x1][y1]1: # 判断是墙直接跳过
return
if nums[x1][y1]!=0: # 如果已经踩过这个了,跳过
return
if x1
x2 and y1y2: # 到了终点
nums[x1][y1]
2
return
if x1<x2:
helper(nums,x1+1, y1, x2, y2)
if y1<y2:
helper(nums, x1, y1+1, x2, y2)
# 陷阱
if x1x2 or y1y2:
if x1x2 and y1<y2 and nums[x1][y1+1]!=2: # 分为横,竖,斜
nums[x1][y1]=9
elif y1
y2 and x1<x2 and nums[x1+1][y1]!=2:
nums[x1][y1]=9
else:
nums[x1][y1]=2
elif nums[x1+1][y]!=2 and nums[x1][y1+1]!=2:
nums[x1][y1]=9
else:
nums[x1][y1]=2
return
helper(nums, 0, 0, m-1, n-1)
trap=0
noway=0
for i in range(m):
for j in range(n):
if nums[i][j]9:
trap+=1
elif nums[i][j]
0: # 走完为0的是不可达
noway+=1
print(trap+" "+noway)

7 最长的指定瑕疵度的元音子串

flaw=int(input())
s=input()
ans=0
idxs=[] # 找出所有端点的位置
for i in range(len(s)):
if i in 'aeiouAEIOU':
idxs.append(i)
count=0
for start in range(len(idxs)-1):
for end in range(start+1, len(idxs)):
temp=s[start: end+1]
for ch in temp:
if ch not in 'aeiouAEIOU':
count+=1
if count==flaw:
ans=max(ans, len(temp))
print(ans)

8 欢乐的周末

m, n=map(int, input().split())
nums=[]
for i in range(m):
nums.append(list(map(int, input().split())))
people=[]
targets=[]
for i in range(m):
for j in range(n):
if nums[i][j]2:
people.append((i, j))
elif nums[i][j]
3:
targets.append((i, j))
h, w=people[0], people[1]
ans=0
def check(x, y, temp):
if xtx and yty:
return 1
if x-1>=0:
if temp[x-1][y]!=1:
temp[x][y]=1 # 能通过设为1,表示本格子已经走过 不过这一步或许不用这么设
if check(x-1, y, temp)1:
return 1
if x+1<len(temp):
if temp[x+1][y]!=1:
temp[x][y]=1
if check(x+1, y, temp):
return 1
if y-1>=0:
if temp[x][y-1]!=1:
temp[x][y]=1
if check(x, y-1, temp)
1:
return 1
if y+1<len(temp[0]):
if temp[x][y+1]!=1:
temp[x][y]=1
if check(x, y+1, temp)==1:
return 1
return 0

for i in targets:
temp=nums[:]
tx=targets[i][0]
ty=targets[i][1]
if check(h[0], h[1], temp)1:
temp=nums[:]
if check(w[0], w[1], temp)
1:
ans+=1
print(ans)

第二种 感觉还是这种简洁点

ans1=[[0]m for _ in range(n)] # 建立2个矩阵,来存储每个人能到的点的坐标
ans2=[[0]
m for _ in range(n)]
px=[-1, 0, 1, 0]
py=[-1, 0, 1, 0]
temp # 用来储存2个人的坐标
def dfs(tmep, ans, i, j, flag):
for idx in range(len(px)):
newx=i+px
newy=i+py
if newx=0 and newy=0 and temp[newx][newy]!=1 and not flag:
temp[newx][newy]=1
ans[newx][newy]=1
dfs(temp, ans, newx, newy, flag)
temp[newx][newy]=0
flag=False
dfs(temp, ans1, temp[0][0], temp[0][1], flag)
flag=False
dfs(temp, ans2, temp[1][0], temp[1][1], flag)
ans=0
for i in range(m):
for j in range(n):
if nums[i][j]3 and ans1[i][j]1 and ans2[i][j]==1:
ans+=1
print(ans)

9 TLV解析II ? 题太长了 答案不是立马能跑的

s=input()
n=int(input())
tags=[]
for i in range(n):
tags.append(int(input()))
def helper(s, tags):
dict={}
ans=['0 0']*len(tags)
i=0
while i<len(s):
tag=int(s[i])
ans=helper(s, tags)
for i in ans:
print(i)

10 服务失效判断

s=input().split(',')
xs=list(map(int, input().split(',')))
sequence=[] # 关系
points=[] # 单个点
for i in s:
sequence.append(i.split('-'))
a=i.split('-')[0]
b=i.split('-')[1]
if a not in points:
points.append(a)
if b not in points:
points.append(b)
for x in xs:
points.remove(x)
ans=[]
def check(sequence, point, X):
if point in X:
return True
for i in range(len(sequence)):
if sequence[i][0]==point and check(sequence, sequence[i][1], X): # 依赖
return True
return False

for point in points:
if not check(sequence, point, X):
ans.append(point)
if len(ans)==0:
print(',')
else:
print(','.join(str(an) for an in ans))

11 数组二叉树

nums=[-1]
ans=[]
nums[1:]=list(map(int, input().split()))
leafNode=[]
for i in range(2, len(nums)):
if nums[i]-1:
continue
elif (2i>len(nums)-1 or nums[2i]
-1 and (2i+1>len(nums)-1 or nums[2i+1]==-1):
leafNode.append(nums[i])
minnode=min(leafNode)
idx=nums.find(minnode)
while idx>0:
ans.append(str(nums[idx]))
idx=idx
ans.reverse()
print(' '.join(ans))

第二种

nums=list(map(int, input().split()))
root=Node(nums[0])
stack=[root]
i=1
while i<len(nums):
r=stack[0]
stack=stack[1:]
r.left=Node(nums[i])
stack.append(r.left)
if i+1<len(nums):
r.right=Node(nums[i+1])
stack.append(r.right)
i+=2
ans=[]
def dfs(r, datas):
if not r or r.data==-1:
ans.append(datas)
return
dfs(r.left, datas+[r.data])
dfs(r.right, datas+[r.data])
dfs(root, [])
ans=sorted(ans, key=lambda x: x[-1])
print(" ".join(map(str, dp[0])))

12 完全二叉树非叶子部分后续遍历

13 最大社交距离

问最后进来的员工,他会坐在第几个位置,如果位置满了,输出-1

num=int(input())
seats=list(map(int, input().split(',')))
c=seats[1: len(seats)-1] # 位置0的人不会离开
seatorleave=[0](len(c))
for i in range(len(c)):
seatorleave=c[i]
def helper(num, seatorleave):
seated=[] # 有序集合记录被坐过的位置
for i in range(len(searorleave)):
op=seatorleave[i]
if op>0: # 对应最下面的remove
if len(seated)0: # 之前已经把位置0排除了,为什么这里还考虑这种情况
if i
len(seatorleave)-1:
return 0
seated.append(0)
elif len(seated)1:
seated.append(num-1)
if i
len(seatorleave)-1:
return num-1
elif len(seated)>1 and len(seated)<num:
ints=[0]
(len(seated))
count=0
for seatednum in seated:
ints[count+=1]=seatednum
maxlen=0
start=0
for j in range(len(ints)):
len=ints[j+1]-ints[j] # 间距
if len/2>maxlen:
maxlen=len/2
start=ints[j]
seated.append(start+maxlen) # 二分法,如果距离相等的两个位置,选idx小的坐
if i==len(seatorleave)-1:
return start+maxlen
else: # 位置坐满
return -1
else:
seated.remove(-op) # 如果是负数,则将该作为移出

ans=helper(num, seatorleave)
print(ans)

14 N进制减法

n, num, jian=input().split()[0], input().split()[1], input().split()[2]
if len(num)!=1 and len(jian)!=1 and (num.startswith('0') or jian.startswith('0')):
print(-1)
if num.endswith('/0'):
num=num[0, len(num)-2]
if jian.endswith('0'):
jian=jian[0, len(jian)-2]
no1=no2=0
no1=int(num, n) # 将num转化为以n为基数的整数
no2=int(jian, n)
else:
print(-1)
ans=no1-no2
if no1-no2>0:
print(0+" ")
else:
print(1+" ")
print(str(ans, jin))

15 简易内存池

n=int(input())
def request(size):
if size<=0 or size>100:
return 'error'
if len(memory)0:
memory.append((0, size-1))
return '0'
else:
bef_start, bef_stop, insert_idx=-1, -1, 0
for start, stop in memory:
if start
0:
pass
elif start-bef_stop-1>=size:
memory.insert(insert_idx, (bef_stop+1, bef_stop+size))
return str(bef_stop+1)
bef_start, bef_stop=start, stop
insert_idx+=1
if bef_stop+size<100:
memory.append((bef_stop+1, bef_stop+size))
return str(bef_stop+1)
else:
return 'error'
def release(start_addr):
found=False
found_couple=(0, 0)
for item in memory:
if item[0]start_addr:
found=True
found_couple=item
break
if found:
memory.remove(found_couple)
return found
memory=[]
for _ in range(n):
command, size=input().split('=')
if command
'REQUEST':
print(pool.request(int(size)))
elif command=='RELEASE':
released=pool.release(int(size))
if not released:
print('error')

16 内存资源分配 只有C++的解 同样题目的题有2道,第二道见后面

17 分糖果II

n=int(input())
a=[int(x) for x in input().split()]
sums=0
for x in a:
sums=sums^x
if sums!=0:
print('NO')
else:
print(sum(a)-min(a))

第二种

n=int(input())
weights=[0]*n
min=float('inf')
sumKoko=0
sum=0
for i in range(n):
x=input()
sum+=x
sumKoko^=x
min=min(min, x)
if sumKoko!=0:
print('NO')
else:
print(sum-min)

18 猜密码

nums=list(map(int, input().split()))
n=int(input())
ans=[]
nums.sort()
for i in range(n, len(nums)+1):
for num in itertools.combinations(nums, i):
ans.append(','.join(map(str, num)))
if len(ans)>0:
for s in sorted(ans):
print(s)
else:
print('none')

第二种

nums=input().replace(' ', '').split(',')
n=int(input())
dp=[]
lens=len(nums)
def dfs(sub):
if len(sub)>=lens:
dp.append(sub)
return
if len(sub)>=n:
dp.append(sub)
for c in nums:
if c not in sub and sub[-1]<c:
dfs(sub+c)
for c in nums:
dfs(c)
for w in dp:
print(w)

19 迷宫问题

mx, my=list(map(int, input().split()))
maze=[input().split() for _ in range(mx)]
def dfs(x, y, add):
if xmx-1 and ymy-1:
print((l[0], l[1]) for l in add)
if x+1<=mx-1 and (x+1, y) not in add and maze[x+1][y]'0':
dfs(x+1, y, add+[(x+1, y)])
if y+1<=my-1 and (x, y+1) not in add and maze[x][y+1]
'0':
dfs(x, y+1, add+[(x, y+1)])
if x-1>=0 and (x-1, y) not in add and maze[x-1][y]'0':
dfs(x-1, y, add+[(x-1, y)])
if y-1>=0 and (x, y-1) not in add and maze[x][y-1]
'0':
dfs(x, y-1, add+[(x, y-1)])
print(dfs(0, 0, [(0, 0)])) # 起点x, 起点y, 答案数组

20 最长方连续方波信号

nums=input()
dp=[]
cache=[]
for c in nums:
if cache and cache[-1]'0'c:
dp.append(''.join(cache))
cache=[c]
else:
cache.append(c)
else:
if cache:
dp.append(''.join(cache))
sub=max(dp, key=lambda x: 0 if '11' in x else len(x))
print(sub)

第二种

s=input()
ans=''
temp=''
b=False
isFomat=True
if s[0]'0':
temp='0'
b=True
for i in range(1, len(s)):
if b:
if s[i]
s[i-1]:
if s[i]'0':
if len(temp)>=3 and isFomat:
ans=str(temp) if len(temp)>len(ans) else ans
temp='0'
isFomat=True
else:
temp.append(s[i])
isFomat=False
else:
temp.append(s[i])
else:
if s[i]
'0':
temp='0'
b=True
print(ans)

21 数据分类

nums=list(map(int, input().split()))
c=nums[0]
b=nums[1]
nums=nums[2:]
dict={}
for i in nums:
strI=str(hex(i))[2:] # hex()把10转换成16进制
length=len(strI)
if length<8:
strI='0'(8-length)+strI
else:
strI=strI[:8]
sum=0
for i in range(4):
sum+=int(strI[i
2: i*2+2], 16)
typeNum=sum%b
if typeNum<c:
if typeNum in dict.keys():
dict[typeNum]+=1
else:
dict[typeNum]=1
print(max(dict.values()))

第二种

ipt=input().split()
c1=ipt[0]
b1=ipt[1]
nums=[0]*(b1-1)
def helper(num):
s=bin(num) # 把整数转化成二进制str
total=0
while len(s)>8:
temp=s[len(s)-8]
total+=int(temp)
s=s[0: len(s)-8]
total+=int(s)
return total
for i in range(2, len(ipt)):
ans=helper(ipt[i])%b1
if ans<c1:
nums[ans]+=1
max=-1
for j in nums:
max=max(max, j)
print(max)

22 统计文本数量

s=input()
f1=False
f2=False
f=False
ans=0
while s:
l=len(s)
for i in range(l):
if s[i]!=' ' and s[i]!=';' and s[i]!='\n':
f=True
if s[i]'-':
if not f1 and not f2 and i!=l-1 and s[i+1]
'-':
break
elif not f1 and not f2 and s[i]';' and f:
ans+=1
f=False
elif s[i]
'"' and i>0 and s[i-1]!='\':
f1=f1^True
elif s[i]=='"' and i>0 and s[i-1]!='\' and not f1:
f2=f2^True
print(ans)

23 贪吃蛇

steps=input().split()
m, n=input().split()[0], input().split()[1]
nums=[]
first=[]
for i in range(m):
nums.append(list(input().split()))
for i in range(n):
for j in range(n):
if nums[i][j]'H':
first.append(i)
first.append(j)
directions={'U':[-1, 0], 'D': [1, 0], 'L': [0, -1], 'R': [0, -1]}
gostep=[0, -1]
snake=[]
for s in range(len(steps)):
temp=steps[s]
if temp
'G':
step=[first[0]+gostep[0], first[1]+gostep[1]]
if step[0]<0 or step[1]<0 or step[0]>=N or step[1]>=M:
break
stepstr=nums[step[0]][step[1]]
if stepstr'F':
nums[first[0]][first[1]]='S'
nums[step[0]][step[1]]='H'
snake.insert(0, first)
first=step
else:
length=len(snake)
if length>0:
tail=snake[length-1]
nums[tail[0]][tail[1]]='E'
snake.pop()
nums[first[0]][first[1]]='H'
snake.insert(0, first)
else:
nums[first[0]][first[1]]='E'
if stepstr
'S':
break
nums[step[0]][step[1]]='H'
first=step
else:
gostep=direction[temp]
print(len(snake)+1)

第二种

start=(0, 0)
for i in range(n):
for j in range(m):
if nums[i][j]'H':
nums[i][j]='E' # 头开始移动之后变为空格
start=(i, j)
body=[start]
direction='L'
for i in steps:
if i
'U':
direction='U'
elif i'D':
direction='D'
elif i
'L':
direction='L'
elif i'R':
direction='R'
elif i
'G':
if direction'U':
next=(body[0][0]-1, body[0][1])
elif direction
'D':
next=(body[0][0]+1, body[0][1])
elif direction'L':
next=(body[0][0], body[0][1]-1)
else:
next=(body[0][0], body[0][1]+1)
if next[0]<0 or next[1]<0 or next[0]>n-1 or next[1]>m-1 or next in body[:-1]:
print(len(body))
if nums[next[0]][next[1]]
'E':
body=[next]+body[:-1]
elif nums[next[0]][next[1]]=='F':
body=[next]+body[:]
nums[next[0]][next[1]]='E' # 吃完以后变成空格
print(len(body))

24 叠积木

nums=list(map(int, input().split()))
n=len(nums)
used=[False]*n
nums.sort()
def helper(length):
level=0
i=j=0
for i in range(n-1, -1, -1):
if nums[i]length:
level+=1
used[i]=True
continue
if used[i]
False:
for j in range(i):
if nums[i]+nums[j]length and used[j]False:
level+=1
used[i]=True
used[j]=True
break
if ji:
for i in range(n):
used[i]=False
return -1
if nums[0]
length:
level+=1
for i in range(n):
if used[i]==False:
level=-1
used[i]=False
return level
ans1=ans2=0
ans1=helper(nums[n-1]) # 一行最多2个, 如果最大的一个除不尽,那只能再加一个最小的,否则其他的组合达不到这么长了
ans2=helper(nums[n-1]+nums[0])
print(max(ans1, ans2))

动规

sum=0
maxVal=nums[-1]
for num in nums:
sum+=num
for i in range(n-1):
if sum%maxVal==0:
break
else:
maxVal+=nums[i]
count=sum/maxVal
sum/=count
dp=[[sum+1] for _ in range(n+1)]
for i in range(n+1):
dp[i][0]=True
for i in range(1, n+1):
for j in range(1, sum+1):
if j-nums[i-1]<0:
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=dp[i-1][j] or dp[i-1][j-nums[i-1]]
if dp[n][sum] and count!=1:
print(count)
else:
print(-1)

力扣 473 拼火柴

totalLen=sum(nums)
if totalLen%40:
return False
nums.sort(reverse=True)
edges=[0]*4
def dfs(idx):
if idx
len(nums):
return True
for i in range(4):
edges[i]+=nums[idx]
if edges[i]<=totalLen//4 and dfs(idx+1):
return True
edges[i]-=nums[idx]
return False
return dfs(0)

25 考古问题

n=int(input())
s=[]
for i in range(n):
s.append(input())

combi=list(itertools.permutations(s, len(s)))
ans=[]
for x in combi:
new=''.join(x)
if new not in ans:
ans.append(new)
print(' '.join(ans))

第二种

def backtrack(s):
if idx==n:
if s not in ans:
ans.append(s[:])
for i in range(idx, n):
s[idx], s[i]=s[i], s[idx]
backtrack(idx+1)
s[idx], s[i]=s[i], s[idx]
backtrack(s)

26 仿LISP运算

nums=input().split()
stacka=[]
stackb=[]
for c in nums:
if '(' in c:
stacka.append('(')
stacka.append(c[1:])
elif ')' in c:
stacka.append(c[:c.index(')')])
stacka+=list(c[c.index(')'):])
else:
stacka.append(c)
while stacka:
temp=stacka.pop()
if temp')':
stackb.append(temp)
elif temp
'(':
com=stackb.pop()
a=int(stackb.pop())
b=int(stackb.pop())
stackb.pop()
if com'add':
stackb.append(a+b)
elif com
'sub':
stackb.append(a-b)
elif com'mul':
stackb.append(a*b)
else:
if b
0:
print('error')
break
stackb.append(a//b)
else:
stackb.append(temp)
if stackb:
print(stackb.pop())

27 九宫格按键输入法

s=input()
dict={'1':',.', '2':'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno',
'7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
num=True
ans=""
i=0
while i<len(s):
if s[i]"#":
num=False
i+=1
continue
if s
"/":
i+=1
continue
if numTrue:
ans+=s[i]
i+=1
continue
if s[i]
'0':
ans+=" "
i+=1
continue
count=1 # 如果有重复的情况,推算出是什么字母
while i<len(s)-1 and s[i]==s[i+1]:
count+=1
i+=1
chs=dic[s[i]]
ans+=chs[count%len(chs)-1]
print(ans)

28 最小传输时延

采用优先队列,维护一个小顶堆,堆需要记录本次访问节点时的延时值,便于判断下一节点是否进行减一操作

m, n=map(int, input().split())
nums=[]
for i in range(m):
nums.append(list(map(int, input().split())))
from heapq import *
def search(nums):
visited=set()
p=[(nums[0][0], 0, 0, nums[0][0])]
visited.add((0, 0))
heapify(p)
while p:
t, i, j, pre=heap.pop(p)
if ilen(nums)-1 and jlen(nums[0])-1:
return t
for newi, newj in [(i-1, j-1), (i-1, j),(i, j-1), (i+1, j+1), (i+1, j), (i, j+1),(i-1, j-1), (i+1, j-1)]:
if 0<=newi<len(nums) and 0<=newj<len(nums[0]):
visited.add((newi, newj))
if pre==nums[newi][newj]:
heappush(p, (t+nums[newi][newj]-1, newi, newj, nums[newi][newj]))
else:
heappush(p, (t+nums[newi][newj], newi, newj, nums[newi][newj]))
ans=search(nums)
print(ans)

29 最长广播效应

n, l=map(int, input().split())
nums=[]
for i in range(n):
nums[i][i]=1
for i in range(l):
row, col=map(int, input().split())
nums[row-1][col-1]=1
nums[col-1][row-1]=1
head=int(input())
ans=0
visited=set()
sequence=[]
sequence.append(head-1)
visited.add(head-1)
while len(visited)<n:
cur=[]
cur.append(sequence)
sequence.clear()
for j in range(len(cur)):
idx=cur[j]
for i in range(n):
if i not in visited and idx!=j and nums[idx][i]1:
visited.add(i)
sequence.append(i)
if len(visited)
n:
break
ans+=1
print(ans*2)

30 完全二叉树非叶子部分后序遍历

31 没有回文串

n=int(input())
s=list(input().split())
exist=False
ans=''
def dfs(cur, idx):
def check(str: cur, idx: n):
for i in range(1, n):
if cur[i]cur[i-1]:
return False
for i in range(2, n):
if cur[i]
cur[i-2]:
return False
return True
if exist:
return
if idx==len(cur):
if cur!=s and check(cur, len(cur)):
exist=True
ans=cur
return
while int(cur[idx]-'a')<n:
if check(cur, idx+1):
dfs(cur, idx+1)
cur[idx]+=1
for i in range(idx+1, len(cur)):
cur[i]='a'
dfs(s, 0)
if exist:
print(ans)
else:
print('NO')

32 打印任务排序

s=input().split(',')
line=[]
ipt=[]
for num in s:
line.append(num)
ipt.append(num)
ans=[]
while len(line)>0:
cur=line.remove(0)
flag=True
for i in range(len(line)):
if line[i]>cur:
line.append(cur)
flag=False
break
if flag==True:
index=ipt.find(cur)
ans.append(index)
print(','.join(str(num) for num in ans))

33 报文解压缩

s=input()
stack=[]
ans=''
multi=0
for ch in s:
if ch'[':
stack.append([multi, ans])
multi=0
ans=''
elif ch
']':
cur_multi, last_ans=stack.pop()
ans=cur_multians+last_ans
elif ch.isdiit():
multi=multi
10+int(ch)
else:
ans+=ch
print(ans)

34 学生方阵

这个完全是我自己写的 不一定对 没跑过

横,纵,正反对角线,共4种情况,看M的学生,最长能连几个人

m, n=list(map(int, input().split()))
nums=[]
for i in range(m):
nums.append(list(input().split(',')))
ans=[]
i=j=0
while i<m:
while j<n:
if nums[i][j]'M':
count=1
if nums[i][j+1]
'M':
end=j
for end in range(j+1, n):
count+=1 if nums[i][end]'M'
j=end+1
ans.append(count)
if nums[i+1][j+1]
'M':
endx=i
endy=j
for endx in range(i+1, m):
for endy in range(j+1, n):
count+=1 if nums[endx][endy]'M'
j+=1
ans.append(count)
while j<n:
while i<m:
if nums[i][j]
'M':
count=1
if nums[i+1][j]'M':
end=i
for end in range(i+1, m):
count+=1 if nums[end][j]
'M'
i=end+1
ans.append(count)
i=0
j=n-1
while i<m:
while j>=0:
if nums[i][j]'M':
count=1
if nums[i+1][j-1]
'M':
endx=i
endy=j
for endx in range(i+1, m):
for endy in range(j-1, -1):
count+=1 if nums[endx][endy]=='M'
i-=1
ans.append(count)
print(max(ans))

35 区间交集

nums=input()
if len(nums)1:
print(nums[0])
nums.sort(key=lambda x: x[0])
ans=[]
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i][1]>=nums[j][0]:
ans.append(nums[i][0], min(nums[i][1], nums[j][1]))
if len(ans)
1:
print(ans)
ans.sort(key=lambda x: x[0])
n=len(ans)
i=0
while i<n-1:
if ans[i][1]>=ans[i+1][0]:
ans[i][1]=max(ans[i][1], ans[i+1][1])
ans.pop(i+1)
n-=1
else:
i+=1
print(ans)

36 任务最优调度

nums=list(map(int, input().split(',')))
n=int(input())
d={}
d_max=0
d_max_n=0
for i in nums:
d[i]=d.get(i, 0)+1
if d[i]>d_max:
d_max=d[i]
for k, v in d.items():
if d[k]==d_max:
d_max_n+=1
print(max((d_max-1)*(n+1)+d_max_n, len(nums)))

37 斗地主之顺子

s=input().split()
nums=[]
for i in s:
if i.isdigit() and i!='2':
nums.append(int(i))
if i'J':
nums.append(11)
if i
'Q':
nums.append(12)
if i'K':
nums.append(13)
if i
'A':
nums.append(14)
nums=sorted(list(set(nums))) #这里或许不用排序
ans=[]
temp=[]
for i in range(len(nums)-1):
if nums[i]+1nums[i+1]:
temp.append(nums[i])
else:
temp.append(nums[i])
if len(temp)>=5:
ans.append(temp)
temp=[]
if len(ans)
0:
print("No")
for temp in ans:
print(" ".join(str(num) for num in temp))

38 最长的顺子

s1=input()
s2=input()
transform={'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10,
'J':11, 'Q': 12, 'K': 13, 'A': 14 }
transform_re={3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10',
11: 'J', 12: 'Q', 13: 'K', 14: 'A'}
mine=[transform.get(x) for x in str(s1).split('-')]
history=[transform.get(x) for x in str(s2).split('-')]
full=[x for x in range(3, 15)]*4
for i in mine+history:
if full[i]:
full.remove(i)
remain=list(set(full))
remain.sort()
temp=[]
ans=[]
for i in range(len(remain)-1):
temp.append(remain[i])
for j in range(i+1, len(remain)):
if remain[j]-remain[j-1]==1:
temp.append(remain[j])
else:
break
if len(temp)>len(ans):
ans=temp[:]
temp=[]
print('-'.join([transform_re[x] for x in ans]))

39 连续出牌数量

nums=input().split()
colors=input().split()
dict={}
for i in range(len(nums)):
if nums[i] not in dict.keys():
dict[nums[i]]={}
dict[nums[i]][i]=colors[i]
if colors[i] not in dict.keys():
dict[colors[i]]={}
dict[colors[i]][i]=nums[i]
ans=[]
temp=[]
def dfs(idx):
if idx in temp:
return
temp.append(idx)
for i in [nums[idx], colors[idx]]:
for key, val in dict[i].items():
dfs(key)
ans.append(len(temp))
temp.pop()
for i in range(len(a)):
dfs(i)
print(max(ans))

40 单词搜索

n, m=map(int, input().split())
s=input()
nums=[]
for i in range(n):
nums.append(list(map(int, input().split())))
directions=[(0, 1), (0, -1), (1, 0), (-1, 0)]
def check(i, j, idx):
if idxlen(s)-1:
return True
visited.add((i, j))
for di, dj in directions:
newi=i+di
newj=j+dj
if 0<=newi<len(nums) and 0<=newj<len(nums[0]):
if (newi, newj) not in visited:
if check(newi, newj, idx+1):
return True
visited.remove((i, j))
return False
visited=set()
for i in range(n):
for j in range(m):
if nums[i][j]
s[0]:
if check(i, j, 0):
print(str(i+1)+" "+str(j+1))
print("NO")

41 高效的任务规划

m=int(input())
for i in range(m):
n=int(input())
for j in range(n):
nums.append(list(map(int, input().split())))
nums=sorted(nums, key=lambda x: x[1], reverse=True)
ans=0
prev=0
for i in range(n):
ans=max(ans, prev+nums[i][0]+nums[i][1])
prev+=nums[i][0]
print(ans)

42 发广播

有两种输入形式: 一行,以逗号分隔为每行的数据; 直接矩阵,空格分隔

nums=list(map(int, input().split(',')))
dict={}
for i in range(len(nums)):
if i in dict.values():
continue
else:
dict[i]=-1
for j in range(len(nums[0])):
if nums[i][j]==1:
dict[i]=j
print(len(dict))

43 内存资源分配

s=input().split(',')
users=list(map(int, input().split()))
ans=[]
spread=[]
for i in s:
each=list(i.split('😂)
for j in range(int(each[1])):
spread.append(int(each[0]))
for user in users:
obtain=[]
for i in spread:
if i>=user:
obtain.append(i)
obtain.sort()
if len(obtain)==0:
ans.append(False)
else:
ans.append(True)
spread.remove(obtain[0])
print(','.join(ans))

44 Directory删除

输出格式到底是一行还是多行; 如果是多行,根目录的ID怎么去除

m=int(input())
nums=[]
dict={}
for i in range(m):
kid, father=input().split()
nums.append((kid, father))
if father in dict:
dict[father].append(kid)
else:
dict[father]=[kid]
def delete(fatheridx):
if fatheridx in dict:
for kididx in dict.pop(fatheridx):
nums.remove((kididx, fatheridx))
delete(kididx)
target=input()
delete(target)
for num in nums:
if num[0]!=target:
print(" ".join(num))

另一种解法

nums.sort()
for i in range(m-1):
if nums[i][0]target:
deleteidx=i
for j in range(deleteidx):
if nums[j][1]
0:
continue
print(nums[j][0]+" "+nums[j][1])

45 比较两个版本号的大小

这个题为什么没有考虑字母的情况呢? 小写字母>大写字母>数字

s1=input().split('.')
s2=input().split('.')
len1=len(s1)
len2=len(s2)
for i in range(min(len1, len2)):
ans=helper(s1[i], s2[i])
if ans!=0:
print(ans)
if len1>len2:
k=len2
while k<len1:
ans=helper(s1[k], "")
if ans!=0:
print(ans)
k+=1
print(0)
if len2>len1:
k=len1
while k<len2:
ans=helper("", s2[k])
if ans!=0:
print(ans)
k+=1
print(0)
def helper(s1, s2):
sb1=""
while len(sb1)>0 and sb1[0]'0':
sb1.remove(0)
sb2=""
while len(sb2)>0 and sb2[0]
'0':
sb2.remove(0)

for i in range(min(len(sb1), len(sb2))):
    if sb1[i]>sb2[i]:
        return 1
    elif sb1[i]<sb2[i]:
        return -1
if len(sb1)>len(sb2):
    k=len(sb2)
    while k<len(sb1):
        if sb1[k]>'0':
            return 1
        k+=1
    return 0
if len(sb2)>len(sb1):
    k=len(sb1)
    while k<len(sb2):
        if sb2[k]>'0':
            return -1
        k+=1
    return 0
return 0

46 移除K位数字的最小值

s=input()
k=int(input())
stack=[]
for digit in s:
while k and stack and stack[-1]>digit:
stack.pop()
k-=1
stack.append(digit)
ans=stack[:len(stack)-k] if k else stack
print("".join(ans).lstrip("0") or "0")

47 转骰子

s=list(input().split())
nums=['1', '2', '3', '4', '5', '6']
def helper(ch):
if ch=='L':
nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]=nums[4],52310
'R' 542301
'F' 014532
'B' 015423
'A' 320145
'C' 231045
return nums
for ch in s:
helper(ch)
print(''.join(ans))

48 面试 这个答案不对,一方面要考虑面试时间是否重合的问题,另一方面要考虑每个面试官最多能面m个人

m=int(input()) # 每个面试官最多面试多少人
n=int(input()) # 总共多少场面试(数据的个数)
nums=[]
for i in range(n):
nums.append(list(map(int, input().split())))
nums=sorted(nums, key=lambda x: x[0])
maxi=max([e for s, e in nums])
ans=[0]*(maxi+1)
for s, e in nums:
for i in range(s, e+1):
ans[i]+=1
print(max(ans))

49 叠书

n=int(input())
nums=[list(map(int, input().split())) for _ in range(n)]
nums=sorted(nums, key=lambda x: x[0])
length=[]
width=[]
for i in nums:
length.append(i[0])
width.append(i[1])
ans=[[0,0]]
for i in range(len(length)):
if length[i]>ans[-1][0]:
a=width[i:]
if width[i]==min(a) and width[i]>ans[-1][1]:
t=[length[i], width[i]]
ans.append(t)
print(len(ans)-1) # 答案是问几本书 这里或许要改一下

第二种

n=int(input())
nums=[]
for i in range(n):
nums.append(list(map(int, input().split())))
ans=[]
lens=len(nums)
def dfs(temp, count=1):
if count>=lens:
ans.append(len(temp))
else:
for i in range(lens):
if i not in temp:
if nums[i][0]<nums[temp[-1][0]] and nums[i][1]<nums[temp[-1][1]]:
dfs(temp+[i], count+1)
for i in range(lens):
dfs([i])
print(max(dp))

50 信道分配

n=int(input())
nums=list(map(int, input().split()))
d=collections.defaultdict(int)
for i in range(len(nums)):
d[2**i]=nums[i]
target=int(input())
ans=0
for k, v in d.items():
if k>=target:
ans+=v
d[k]=0
t=target
for k, v in sorted(d.items(), key=lambda x: x[0]):
while v>0:
t-=k
v-=1
if t<=0:
ans+=1
t=target
print(ans)

第二种

r=int(input())
nums=list(map(int, input().split()))
d=int(input())
ans=0
lst=[]
for i in range(r+1):
for j in range(nums[i]):
num=2**i # 信道容量
if num>=0: # 信道容量大于用户需求时 直接满足
ans+=1
continue
lst.append(num)
isenough=True # 是否够一个用户使用
while isenough:
count=lst[len(lst)-1] # 取最大的信道
lst.remove(lst[len(lst)-1]) # 取完需要剔除
while count<d and isenough:
minn=float('inf')
minindex=0
temp=0
for i in range(len(lst)):
temp+=lst[i]
diff=abs(d-count-lst[i]) # 求出与所需信道最接近的信道
minn=min(minn, diff)
if minn=diff:
minindex=i
count+=lst[minindex]
lst.remove(lst[minindex])
if count>=d:
ans+=1
break
if count+temp<d: # 总共的信道不够一个用户使用
isenough=False
print(ans)

51 污染水域 和力扣腐烂的橘子 很像了

s=list(map(int, input().split(',')))
if not s.find(0):
print(-1)
if not s.find(1):
print(-1)
length=len(s)
i=1
n=0
for i in range(1, length):
if i*ilength:
n=i
nums=[]
while length>0:
nums.append(s[:i])
s=s[i:]
queue=[]
fresh=0
for i in range(n):
for j in range(n):
if nums[i][j]
0:
fresh+=1
elif nums[i][j]1:
queue.append((i, j))
time=0
while fresh>0 and len(queue)>0:
time+=1
N=len(queue)
for _ in range(N):
i, j=queue.pop()
if i-1>=0 and nums[i-1][j]
0:
nums[i-1][j]=1
fresh-=1
queue.append((i-1, j))
if i+1<n and nums[i+1][j]0:
nums[i+1][j]=1
fresh-=1
queue.append((i+1, j))
if j-1>=0 and nums[i][j-1]
0:
nums[i][j-1]=1
fresh-=1
queue.append((i, j-1))
if j+1<n and nums[i][j+1]==0:
nums[i][j+1]=1
fresh-=1
queue.append((i, j+1))
print(time)

52 字符串匹配

nums=input().split()
line=input()
ans=[]
def check(s1, s2):
i=j=0
while i<len(s1) and j<len(s2):
if s1[i]s2[j] or s1[i]'.':
i+=1
j+=1
continue
if s1[i]!='.' and s1[i]!='' and s1[i]!=s2[j]:
return False
if s1[i]=='
':
i+=1
if i>=len(s1):
return True
else:
if s1[i]==s2[j]:
j+=1
while s1[i]!=s2[j]:
if s1[i]='.':
j+=1
break
else:
j+=1
if j>=len(s2):
return False
return True
for i in range(len(nums)):
if check(line, nums[i]):
ans.append(i)
if ans:
print(",".join(sorted(ans)))
else:
print(-1)

53 最小传输时延

n, m=map(int, input().split())
nums=[]
for i in range(m):
nums.append(list(map(int, input().split())))
start, end=map(int, input().split())
g=[[float('inf')]* n for _ in range(n)] # 不太明白这个g的用途?
for x, y, time in nums:
g[x-1][y-1]=time
dist=[float('inf')]n
dist[start-1]=0
used=[False]
n
for _ in range(n):
x=-1
for y, u in enumerate(used):
if not u and (x==-1 or dist[y]<dist[x]):
x=y
used[x]=True
for y, time in enumerate(g[x]):
dist[y]=min(dist[y], dist[x]+time)
ans=dist[end-1]
print(ans)

以下或许不是200分的题,为了更新方便放在了这个位置,可看题解难易程度估计一下分值

5 最大岛屿体积

row, col=map(int, input().split())
nums=[]
for i in range(row):
nums.append(list(map(int, input().split())))
ans=0
def dfs(nums, i, j):
row=len(nums)
col=len(nums[0])
if i<0 or i>=row or j<0 or j>=col or nums[i][j]==0:
return
area+=nums[i][j]
dfs(nums,i-1, j)
dfs(nums,i+1, j)
dfs(nums,i, j-1)
dfs(nums,i, j+1)
for i in range(row):
for j in range(col):
if nums[i][j]>0:
area=0
dfs(nums, i, j)
ans=max(ans, area)
print(ans)

6 机智的外卖员

n, m=map(int, input().split())
if n>=m:
print(0)
dp=[0]*(m+1) # 到第i层的最短时间
dp[0]=0
for i in range(n+1): # 步行向下
dp[i]=n-i
for i in range(n+1, m+1):
if i%2==0:
dp[i]=min(dp[i-1]+1, dp[i/2]+1)
else:
dp[i]=min(dp[i-1]+1, dp[(i+1)/2]+2)
print(dp[m])

8 DNA序列

s=list(input().split())
n=int(input())
start=0
count=0
maxi=0
for i in range(n):
if s[i]'C' or s[i]'G':
count+=1
maxi=count
left=1
right=n
while left<right:
if s[left-1]'C' or s[left-1]'G':
count-=1
if s[right]'C' or s[right]'G':
count+=1
if count>maxi:
maxi=count
start=left
left+=1
right+=1
print(s[start: start+n])

9 整数最小和 同100分的11题

s=list(input().split())
ans=0
for i in range(len(s)):
c=s[i]
if c.isdigit():
ans+=int(c)
if c=='-':
temp=''
i=0
while i<len(s) and s[i].isdigit():
temp.append(s[i])
i-=1
if len(temp)>0:
sum-=int(temp)
print(ans)

第二种

s=list(input().split())
ans=0
flag=False # 负数
temp=''
for c in s:
if c>='0' and c<='9':
if flag:
temp.append(c)
else:
ans+=int(c)
elif c'-':
if flag:
if not len(temp)
0: # 遇到负号后,将负号后的连续数组成字符串
ans-=int(temp)
temp=''
flag=True
else:
flag=False # 用来判断负号后的字符串结束
if not len(temp)0: # 队列不空,说明负号字符串到此为止
ans-=int(temp)
temp=''
if flag:
if not len(temp)
0:
ans-=int(temp)
print(ans)

11 猴子吃桃

nums,h=list(map(int, input().split()))
if len(nums)>h:
print(-1)
else:
for i in range(1, max(nums)+1)::
if sum([int(n/i+0.5) for n in nums])<=h:
print(i)
break
else:
print(-1)

第二种

ipt=input().split()
nums=[0]*(len(ipt)-1)
for i in range(len(ipt)-1):
for j in range(len(ipt[i])):
ch=ipt[i][j]
if ch>='0' and ch<='9':
continue
else:
print(-1)
nums[i]=int(ipt[i])
h=int(ipt[len(ipt)-1])
nums.sort()
left=1
right=nums[len(nums)-1]
def check(nums, h, k):
time=0
for num in nums:
time+=(num+k-1)/k
return time<=h
while left<right:
mid=left+(right-left)/2
if not check(nums, h, mid):
left=mid+1
else:
right=mid
print(left)

12 最多团队

n=int(input())
list1=list(map(int, input().split()))
list1.sort(reverse=True)
n=int(input().split())
i, j, ans=0, n-1, 0
whiel i<j:
if list1[i]>=n:
ans+=1
i+=1
elif list1[i]+list1[j]>=n:
ans+=1
i+=1
j-=1
else:
j-=1
print(ans)

13 分月饼

m, n=map(int, input().split())
if m>n:
print(0)
p=n-m
count=0
def helper(m, p, k):
if p<=0:
return 0
if m<0:
return 0
if m==1:
if p>=k and p<=k+3:
return 1
return 0
ncount=0
knext=k
for knext in range(k, k+4):
ncount=ncount+helper(m-1, p-knext, knext)
return ncount
for i in range(p):
count=count+helper(m-1, p-i, i)
print(count)

posted @ 2023-04-21 15:16  进击的bug~  阅读(40)  评论(0编辑  收藏  举报