Stripe 编码题整理:最多一个中转国家的最低运费

国家间运费:直达或最多经一个中转国家,求总成本最低的路线、运输方式与总成本。

2025-12OAVO Helper · 面经整理

01 · QUESTIONS

面试题目

  • 给出国家之间可用的运输方式及各自的成本,同一对国家之间可能有多种运输方式。
  • 从起点国家到终点国家,选择总成本最低的路线:可以直达,或者最多经过一个中转国家。
  • 返回运输路线、每段使用的运输方式,以及总成本。

02 · ANSWERS

参考答案

跳数最多为 2,不需要通用最短路:先对每对国家只保留最便宜的运输方式,再比较「直达」与「经过每个可能的中转国家」的总成本。

解题思路

  • 预处理:best[(a, b)] = (成本, 方式),同一对国家只保留最便宜的方式。
  • 直达:查 best[(src, dst)];一次中转:枚举所有从 src 出发的边 (src, mid),再查 (mid, dst)。
  • 枚举是完整的:任何合法路线要么直达,要么是 src → mid → dst,两类都被覆盖。

代码

from collections import defaultdict

def cheapest_route(routes, src, dst):
    """routes: [(from, to, method, cost), ...]"""
    best = {}
    out = defaultdict(set)
    for a, b, method, cost in routes:
        if (a, b) not in best or cost < best[(a, b)][0]:
            best[(a, b)] = (cost, method)
        out[a].add(b)
    answer = None
    if (src, dst) in best:
        c, m = best[(src, dst)]
        answer = (c, [src, dst], [m])
    for mid in out[src]:
        if mid in (src, dst) or (mid, dst) not in best:
            continue
        c1, m1 = best[(src, mid)]
        c2, m2 = best[(mid, dst)]
        if answer is None or c1 + c2 < answer[0]:
            answer = (c1 + c2, [src, mid, dst], [m1, m2])
    if answer is None:
        return None
    cost, path, methods = answer
    return {'route': path, 'methods': methods, 'cost': cost}

复杂度

  • 时间:O(E),E 为运输方式条数。
  • 空间:O(E)。

联系 OAVO Helper

想针对这题做模拟练习?

加微信咨询陪跑,我们可以按你的目标岗位安排简历、模拟面试或代投。

加微信咨询陪跑微信:aasummer