算法学习记录3

L1-077 大笨钟的心情 
mood_levels = list(map(int, input().split()))

# 存储询问时间点
lines = []

# 获取询问时间点,直到遇到非法输入
while True:
    ask_time = input()
    if ask_time == "":
        break
    lines.append(int(ask_time))

# 遍历询问时间点并判断对应心情指数
for time in lines:
    if 0 <= time < len(mood_levels):  # 检查时间点是否有效
        mood = mood_levels[time]
        if mood > 50:
            print("{} Yes".format(mood))
        else:
            print("{} No".format(mood))

L1-078 吉老师的回归
num, did = map(int,input().split())

valid_problems = []

for _ in range(num):
    str_quest = input()

    if str_quest.find('qiandao') == -1 and str_quest.find('easy') == -1:
        valid_problems.append((str_quest))

if did < len(valid_problems):
    print(valid_problems[did])
else:
    print("Wo AK le")

L1-079 天梯赛的善良
stu_num = int(input())
ability = list(map(int, input().split()))

if len(ability) == stu_num:
    # math.inf 正无穷大的浮点数,负无穷大,使用 -math.inf 。
    # math.inf 相当于 float('inf') 的输出。
    # 将最小值初始化为一个比较大的数,将最大值初始化为一个比较小的数,
    # 以确保能正确找到最小值和最大值。
    min_num = float('inf')
    max_num = float('-inf')
    min_count = 0
    max_count = 0

    for num in ability:
        if num < min_num:
            min_num = num
            min_count = 1
        elif num == min_num:
            # 如果当前遍历到的数字 num 等于当前已知的最小值 min_num,
            # 说明找到了另一个与当前最小值相同的数字。
            min_count += 1

        if num > max_num:
            max_num = num
            max_count = 1
        elif num == max_num:
            max_count += 1

    print("{} {}".format(min_num, min_count))
    print("{} {}".format(max_num, max_count))

L1-080 乘法口诀数列
def generate_sequence(a1, a2, n):
    a = [a1, a2]  # 初始数组
    index = 0  # 开始计算乘积的索引位置

    # 生成序列直到长度为 n
    while len(a) < n:
        t = a[index] * a[index + 1]  # 相邻元素相乘
        if t >= 10:
            a.append(t // 10)  # 存储十位
            if len(a) < n:  # 检查数组长度,防止超出 n
                a.append(t % 10)  # 存储个位
        else:
            a.append(t)
        index += 1  # 移动到下一个元素对

    # 输出整个数组
    print(' '.join(map(str, a[:n])))

if __name__ == "__main__":
    a1, a2, n = map(int, input().split())
    generate_sequence(a1, a2, n)

L1-082 种钻石
def calculate_days_needed(N,V):
    days_needed = N // V
    return days_needed

N,V = map(int,input().split())

days_needed = calculate_days_needed(N,V)
print(days_needed)
L1-083 谁能进图书馆
a,b,c,d=map(int,input().split())
e=max(c,d)
f=min(c,d)
g=[]
g.append(f)
g.append(e)
g[0]=1
g[1]=2
if f<a and e>=b:
    if c>=d:
        print("%d-Y %d-Y"%(c,d))
        print("qing %d zhao gu hao %d"%(int(g[0]),int(g[1])))
    else:
        print("%d-Y %d-Y"%(c,d))
        print("qing %d zhao gu hao %d"%(int(g[1]),int(g[0])))
elif f>=a:
    print("%d-Y %d-Y"%(c,d))
    print("huan ying ru guan")
elif e<a:
    print("%d-N %d-N"%(c,d))
    print("zhang da zai lai ba")
else:
    if c<d:
        print("%d-N %d-Y"%(f,e))
        print("%d: huan ying ru guan"%(int(g[1])))
    else:
        print("%d-Y %d-N"%(e,f))
        print("%d: huan ying ru guan"%(int(g[0])))

L1-085 试试手气
a = [0] * 6
input_values = input().split()
for i in range(6):
    a[i] = int(input_values[i])
n = int(input())
t = 7 - n
for i in range(6):
    if a[i] >= t:
        a[i] = t - 1
    else:
        a[i] = t
print(" ".join(str(x) for x in a))

L1-086 斯德哥尔摩火车上的题
def process_string(a):
    s = ''
    for i in range(1, len(a)):
        if int(a[i]) % 2 == int(a[i-1]) % 2:
            s += max(a[i], a[i-1])
    return s

# 读取输入
string1 = input().strip()
string2 = input().strip()

# 处理字符串
result1 = process_string(string1)
result2 = process_string(string2)

# 判断结果是否相同
if result1 == result2:
    print(result1)
else:
    print(result1)
    print(result2)

L1-087 机工士姆斯塔迪奥
row, col, chose = map(int, input().split())
total_safe = row * col
unsafe_rows = set()
unsafe_cols = set()
# 在集合中,每个元素都是唯一的,重复的元素会被自动去重
for _ in range(chose):
    t, q = map(int, input().split())
    if t == 0:
        unsafe_rows.add(q)
    elif t == 1:
        unsafe_cols.add(q)

# 计算不安全的行和列对应的格子数量
unsafe_spaces = len(unsafe_rows) * col + len(unsafe_cols) * row

# 减去重复计算的格子数量
overlap = len(unsafe_rows) * len(unsafe_cols)

# 安全格子数量等于总格子数减去不安全格子数量再加上重复计算的格子数量
final_safe = total_safe - unsafe_spaces + overlap
print(final_safe)

L1-088 静静的推荐
N,K,S = map(int,input().split())
count = 0
dic = dict()
for _ in range(N):
    key,pat = map(int,input().split())
    if key >= 175:
        if pat >= S:
            count += 1
        else:
            dic[key] = dic.get(key,0) + 1
for value in dic.values():
    count += K if K <= value else value
print(count)

# plan B right
_, demand = map(int, input().split())
mooncakes = sorted(zip(map(float, input().split()), map(float, input().split())), key=lambda x: x[1]/x[0], reverse=True)
income = 0
for storage, price in mooncakes:
    if demand >= storage:
        demand -= storage
        income += price
    else:
        income += demand * (price / storage)
        break
print(f'{income:.2f}')

L2-001 城市间紧急救援
import heapq
from collections import defaultdict, deque


def read_input():
    Nv, Ne, st, ed = map(int, input().split())
    costs = list(map(int, input().split()))
    Adj = defaultdict(list)
    for _ in range(Ne):
        u, v, w = map(int, input().split())
        Adj[u].append((v, w))
        Adj[v].append((u, w))
    return Nv, Ne, st, ed, costs, Adj


def dijkstra(Nv, Adj, st):
    dist = [float('inf')] * Nv
    dist[st] = 0
    pq = [(0, st)]  # (distance, vertex)
    visited = [False] * Nv
    pre = defaultdict(list)

    while pq:
        d, u = heapq.heappop(pq)
        if visited[u]:
            continue
        visited[u] = True
        for v, w in Adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(pq, (dist[v], v))
                pre[v] = [u]
            elif d + w == dist[v]:
                pre[v].append(u)
    return dist, pre


def dfs(ed, st, pre, costs):
    def explore(u):
        if u == st:
            temp_path.append(u)
            temp_value = sum(costs[i] for i in temp_path)
            nonlocal max_value, num_paths, best_path
            if temp_value > max_value:
                max_value = temp_value
                best_path = temp_path.copy()
            num_paths += 1
            temp_path.pop()
            return

        temp_path.append(u)
        for v in pre[u]:
            explore(v)
        temp_path.pop()

    num_paths = 0
    max_value = 0
    best_path = []
    temp_path = []
    explore(ed)
    return num_paths, max_value, best_path


def print_result(num_paths, max_value, best_path):
    print(num_paths, max_value)
    print(' '.join(map(str, best_path[::-1])))


def main():
    Nv, Ne, st, ed, costs, Adj = read_input()
    dist, pre = dijkstra(Nv, Adj, st)
    num_paths, max_value, best_path = dfs(ed, st, pre, costs)
    print_result(num_paths, max_value, best_path)


if __name__ == "__main__":
    main()

L2-002 链表去重
class Node:
    def __init__(self):
        self.key = 0
        self.nextid = 0

def main():
    no = [Node() for _ in range(100000)]  # 存放原始链表
    n = 0
    r1 = 0
    r2 = 0
    id = 0
    h1 = 0
    key = [0] * 100000  # key数组表示是否遇到过此key绝对值
    nextid = [0] * 100000  # nextid存放去重后ID
    nextid1 = [0] * 100000  # nextid1存放去掉的ID

    h1, n = map(int, input().split())
    for i in range(n):
        input_list = input().split()
        id = int(input_list[0])
        no[id].key, no[id].nextid = map(int, input_list[1:])

    while h1 != -1:  # 遍历链表
        if key[abs(no[h1].key)]:  # 如果key绝对值遇到过,将当前ID放入数组nextid1中
            nextid1[r2] = h1
            r2 += 1
            nextid1[r2] = -1  # 使存放当前ID的下一个数组元素等于-1,为输出准备
            h1 = no[h1].nextid  # 改变h1使得链表向后遍历
        else:  # 否则将ID放入数组nextid中
            key[abs(no[h1].key)] = 1
            nextid[r1] = h1
            r1 += 1
            nextid[r1] = -1
            h1 = no[h1].nextid

    for i in range(r1):  # 遍历输出key值去重后的链表
        if nextid[i + 1] != -1:
            print('{:05d} {} {:05d}'.format(nextid[i], no[nextid[i]].key, nextid[i + 1]))
        else:  # 如果nextid[i+1]==-1,则在输出它的时候不需要强制输出五位
            print('{:05d} {} {}'.format(nextid[i], no[nextid[i]].key, nextid[i + 1]))

    for i in range(r2):  # 遍历输出去掉的链表
        if nextid1[i + 1] != -1:
            print('{:05d} {} {:05d}'.format(nextid1[i], no[nextid1[i]].key, nextid1[i + 1]))
        else:
            print('{:05d} {} {}'.format(nextid1[i], no[nextid1[i]].key, nextid1[i + 1]))

if __name__ == "__main__":
    main()

L2-003 月饼
def money_mooncake_greedy(cake_storage, cake_sale, market_need):
    # 使用 zip 结合库存量和总售价,并按单价(总售价/库存量)从高到低排序
    cakes = sorted(zip(cake_storage, cake_sale), key=lambda x: x[1] / x[0], reverse=True)

    total_demand = 0
    total_revenue = 0

    for storage, sale in cakes:
        # 在不超出市场需求的前提下,尽可能多地销售当前月饼
        sellable_amount = min(storage, market_need - total_demand)
        total_demand += sellable_amount
        total_revenue += sellable_amount * (sale / storage)

        # 如果市场需求已满足,停止销售
        if total_demand >= market_need:
            break

    return round(total_revenue, 2)

if __name__ == "__main__":
    cake_type, market_need = map(int, input().split())
    cake_storage = list(map(int, input().split()))
    cake_sale = list(map(int, input().split()))
    revenue = money_mooncake_greedy(cake_storage, cake_sale, market_need)
    print(revenue)

L2-004 这是二叉搜索树吗?
def get_postorder(pre, l, r, is_mirror):
    if l > r:
        return True, []
    # 寻找子树的界限
    i = l + 1
    j = r
    if not is_mirror:
        while i <= r and pre[i] < pre[l]:
            i += 1
        while j > l and pre[j] >= pre[l]:
            j -= 1
    else:
        while i <= r and pre[i] >= pre[l]:
            i += 1
        while j > l and pre[j] < pre[l]:
            j -= 1

    if i - j != 1:
        return False, []

    # 递归获取左右子树的后序遍历
    left_valid, left_post = get_postorder(pre, l + 1, j, is_mirror)
    right_valid, right_post = get_postorder(pre, i, r, is_mirror)
    if not left_valid or not right_valid:
        return False, []

    # 当前节点的值追加到后序列表中
    return True, left_post + right_post + [pre[l]]


def main():
    n = int(input())
    pre = list(map(int, input().split()))

    # 尝试作为正常的二叉搜索树处理
    valid, post = get_postorder(pre, 0, n - 1, False)
    if not valid:
        # 尝试作为镜像二叉搜索树处理
        valid, post = get_postorder(pre, 0, n - 1, True)

    if valid and len(post) == n:
        print("YES")
        print(" ".join(map(str, post)))
    else:
        print("NO")


if __name__ == "__main__":
    main()

#测试点五
#非零返回
L2-005 集合相似度
def calculate_similarity(set1, set2):
    common_elements = len(set1.intersection(set2))
    total_elements = len(set1.union(set2))
    similarity = common_elements / total_elements * 100
    return round(similarity, 2)

def main():
    N = int(input())  # 集合的个数
    sets = {}  # 存储集合信息的字典

    # 读取集合信息并存储在字典中
    for i in range(N):
        elements = set(map(int, input().split()[1:]))
        sets[i+1] = elements

    K = int(input())  # 需要计算相似度的集合对数

    # 计算相似度并输出结果
    for _ in range(K):
        set1_num, set2_num = map(int, input().split())
        set1 = sets[set1_num]
        set2 = sets[set2_num]
        similarity = calculate_similarity(set1, set2)
        print("{:.2f}%".format(similarity))

if __name__ == "__main__":
    main()

L2-006 树的遍历
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


def build_tree(inorder, postorder):
    if not postorder:
        return None
    root_value = postorder[-1]
    root = TreeNode(root_value)
    mid_idx = inorder.index(root_value)

    root.left = build_tree(inorder[:mid_idx], postorder[:mid_idx])
    root.right = build_tree(inorder[mid_idx + 1:], postorder[mid_idx:-1])

    return root


def level_order_traversal(root):
    if not root:
        return []
    from collections import deque
    queue = deque([root])
    level_order = []

    while queue:
        node = queue.popleft()
        level_order.append(node.data)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

    return level_order


if __name__ == '__main__':
    node_count = int(input())
    post_order = list(map(int, input().split()))
    in_order = list(map(int, input().split()))

    root = build_tree(in_order, post_order)
    result = level_order_traversal(root)
    print(' '.join(map(str, result)))
L2-007 家庭房产
class Person:
    def __init__(self, id, parent1, parent2, children, houses, area):
        self.id = id
        self.parent1 = parent1
        self.parent2 = parent2
        self.children = children
        self.houses = houses
        self.area = area

def get_family_info(person, people, family_info):
    family_id = person.parent1 if person.parent1 != -1 else person.id
    if family_id not in family_info:
        family_info[family_id] = {
            'members': set(),
            'house_count': 0,
            'total_area': 0
        }
    family = family_info[family_id]

    family['members'].add(person.id)
    family['house_count'] += person.houses
    family['total_area'] += person.houses * person.area

    for child_id in person.children:
        if child_id in people:  # 检查子女编号是否存在于输入中
            get_family_info(people[child_id], people, family_info)

def main():
    N = int(input())
    people = {}
    family_info = {}

    for _ in range(N):
        id, parent1, parent2, child_count, *children_houses_area = map(int, input().split())
        children = children_houses_area[:child_count]
        houses_area = children_houses_area[child_count:]
        houses = houses_area[::2]
        area = houses_area[1::2]
        person = Person(id, parent1, parent2, children, sum(houses), sum(area))
        people[id] = person

    for person in people.values():
        get_family_info(person, people, family_info)

    families = sorted(family_info.items(), key=lambda x: (-x[1]['total_area'], min(x[1]['members'])))

    print(len(families))
    for family_id, info in families:
        population = len(info['members'])
        house_count = info['house_count']
        average_area = info['total_area'] / population
        print("{:04d} {} {:.3f} {:.3f}".format(family_id, population, house_count / population, average_area))

if __name__ == "__main__":
    main()
L2-008 最长对称子串
def find_longest_symmetric_substring_length(string):
    n = len(string)
    if n == 0:
        return 0

    # 创建一个二维数组用于存储子串是否是回文子串的信息
    dp = [[False] * n for _ in range(n)]

    max_length = 1  # 默认回文子串长度为1

    # 单个字符都是回文子串
    for i in range(n):
        dp[i][i] = True

    # 计算长度为2的回文子串
    for i in range(n - 1):
        if string[i] == string[i + 1]:
            dp[i][i + 1] = True
            max_length = 2

    # 计算长度大于等于3的回文子串
    for length in range(3, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            if string[i] == string[j] and dp[i + 1][j - 1]:
                dp[i][j] = True
                max_length = length

    return max_length


input_str = input()
longest_length = find_longest_symmetric_substring_length(input_str)
print(longest_length)
L2-010 排座位
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def merge(self, x, y):
        rootX = self.find(x)
        rootY = self.find(y)
        if rootX != rootY:
            self.parent[rootX] = rootY


def main():
    import sys
    input = sys.stdin.read
    data = input().split()

    idx = 0

    n = int(data[idx])
    idx += 1
    m = int(data[idx])
    idx += 1
    k = int(data[idx])
    idx += 1

    c = [[0] * (n + 1) for _ in range(n + 1)]
    uf = UnionFind(n + 1)

    for _ in range(m):
        a = int(data[idx])
        idx += 1
        b = int(data[idx])
        idx += 1
        r = int(data[idx])
        idx += 1

        c[a][b] = r
        c[b][a] = r
        if r == 1:
            uf.merge(a, b)

    results = []
    for _ in range(k):
        a = int(data[idx])
        idx += 1
        b = int(data[idx])
        idx += 1

        if c[a][b] == 1:
            results.append("No problem")
        elif c[a][b] == -1 and uf.find(a) == uf.find(b):
            results.append("OK but...")
        elif c[a][b] == -1 and uf.find(a) != uf.find(b):
            results.append("No way")
        elif c[a][b] == 0 and uf.find(a) != uf.find(b):
            results.append("OK")

    for result in results:
        print(result)


if __name__ == "__main__":
    main()

L2-011 玩转二叉树
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def build_tree(inorder, preorder):
    if not inorder or not preorder:
        return None
    root_val = preorder[0]
    root = TreeNode(root_val)
    root_index = inorder.index(root_val)
    root.left = build_tree(inorder[:root_index], preorder[1:1 + root_index])
    root.right = build_tree(inorder[root_index + 1:], preorder[1 + root_index:])
    return root

def mirror_tree(root):
    if root:
        root.left, root.right = mirror_tree(root.right), mirror_tree(root.left)
    return root

def level_order_traversal(root):
    if not root:
        return []
    result = []
    queue = [root]
    while queue:
        node = queue.pop(0)
        result.append(node.val)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return result

# 读取输入
n = int(input())
inorder = list(map(int, input().split()))
preorder = list(map(int, input().split()))

# 构造二叉树
root = build_tree(inorder, preorder)

# 镜面反转
root = mirror_tree(root)

# 层序遍历输出
result = level_order_traversal(root)
print(' '.join(map(str, result)))

L2-012 关于堆的判断
def checkHeap(heap, target):
    if target == 0:
        return heap
    if heap[target] < heap[(target - 1) // 2]:
        temp = heap[target]
        heap[target] = heap[(target - 1) // 2]
        heap[(target - 1) // 2] = temp
    heap = checkHeap(heap, (target - 1) // 2)
    return heap

def heapInsert(heap, value, _index):
    heap[_index] = value
    return checkHeap(heap, _index)


n, m = map(int, input().split())
heap = [None for i in range(n)]
values = list(map(int, input().split()))
for i, item in enumerate(values):
    heap = heapInsert(heap, item, i)
for i in range(m):
    command_words = input().split()
    if 'root' in command_words:
        print('T') if heap[0] == int(command_words[0]) else print('F')
    elif 'siblings' in command_words:
        print('T') if ((heap.index(int(command_words[0])) - 1) // 2) == ((heap.index(int(command_words[2])) - 1) // 2) else print('F')
    elif 'parent' in command_words:
        print('T') if heap.index(int(command_words[0])) == ((heap.index(int(command_words[-1])) - 1) // 2) else print('F')
    else:
        print('T') if heap.index(int(command_words[-1])) == (heap.index(int(command_words[0])) - 1) // 2 else print('F')

谢谢阅读😎

有错请指出😄

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值