classSolution: defsecondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int: # 建圖 g = [[] for _ inrange(n)] for u, v in edges: u, v = u - 1, v - 1 g[u].append(v) g[v].append(u)
# BFS 維護最短路徑與次短路徑 dis = [[float('inf')] * 2for _ inrange(n)] # (最短路徑, 次短路徑) dis[0][0] = 0 q = deque([(0, 0)]) # (node, distance) while q: u, d = q.popleft() switch = d // change # 紅綠燈的切換次數 if switch & 1: # 當前是紅燈,需要等待切換為綠燈才能出發 nd = (switch + 1) * change + time else: # 當前是綠燈,可以直接出發 nd = d + time for v in g[u]: if nd < dis[v][0]: # new_d 比最短路徑小,就更新最短路徑 dis[v][0] = nd q.append((v, nd)) elif dis[v][0] < nd < dis[v][1]: # new_d 比最短路徑大又比次短路徑小,就更新次短路徑 dis[v][1] = nd q.append((v, nd)) return dis[n-1][1]
classSolution { public: intsecondMinimum(int n, vector<vector<int>>& edges, int time, int change){ vector<vector<int>> g(n); for (auto& e : edges) { int u = e[0]-1, v = e[1]-1; g[u].push_back(v); g[v].push_back(u); } vector<vector<int>> dis(n, vector<int>(2, INT_MAX / 2)); dis[0][0] = 0; deque<pair<int, int>> q; q.push_back({0, 0}); while (!q.empty()) { int u = q.front().first, d = q.front().second; q.pop_front(); int sw = d / change; int nd = sw & 1? (sw + 1) * change + time : d + time; for (int v : g[u]) { if (dis[v][0] > nd) { dis[v][0] = nd; q.push_back({v, nd}); } elseif (dis[v][0] < nd && dis[v][1] > nd) { dis[v][1] = nd; q.push_back({v, nd}); } } } return dis[n-1][1]; } };
寫在最後
masterpiece, best quality, high quality, extremely detailed CG unity 8k wallpaper, extremely detailed, High Detail,
1 girl, solo, long hair, black hair, blue eyes, skirt, shirt, school uniform, standing, white shirt, short sleeves, pleated skirt, outdoors, sky, serafuku, (pink serafuku, pink school uniform), day, sailor collar, blurry, arm up, neckerchief, long skirt, girl