题目
链接: link
第一次做算法笔试题,做完之后反思下
第一题(92%超时)
import heapq
def select_data(data , N):
heap=[]
for num in data:
if len(heap) < N:
heapq.heappush(heap, num)
elif num >heap[0]:
heapq.heapreplace(heap, num)
heap.sort(reverse=True)
result = ''.join(str(num) for num in heap)
return result, heap
data = []
N, _ = map(int, input().split())
while True:
try:
a, b = map(int,input().split())
data.append([b for _ in range(a)])
except:
break
heap=[]
for cur_batch in data:
heap = heap + cur_batch
res_data, heap = select_data(heap, N)
print(res_data)
第二题
自己想的动态规划法
def my_minisum_squares(m, n):
if m == n:
return 1
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1, n+1):
if i < j:
dp[i][j] = 1 + dp[i][j - (j+1)//2]
elif i > j:
dp[i][j] = 1 + dp[i - (i+1)//2][j]
else:
dp[i][j] = 1
print(dp)
return dp[m][n]
def func():
m= int(input())
n = int(input())
min_regions = my_minisum_squares(m, n)
print(min_regions)
if __name__ == "__main__":
func()
后来写的,只验证了示例,其他不知道对不对
第三题
没啥好说的,四个for循环,遍历四个变量:位置i,j和矩阵大小m,n,去计算cost,求最小cost