到达目的地的第二短时间
2045.到达目的地的第二短时间
题目描述
到达目的地的第二短时间
思路
BFS
因为time和change是固定的,所以可以统计出起点到终点的最短距离和次短距离,然后根据次短距离计算答案。
Python实现
class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
graph = defaultdict(set)
for a, b in edges:
graph[a].add(b)
graph[b].add(a)
pq = deque([(1, 0)])
explored = [[inf] * 2 for i in range(n)]
explored[0][0] = 0
while pq:
idx, dist = pq.popleft()
for other in graph[idx]:
# 第一次到达
if dist + 1 < explored[other - 1][0]:
explored[other - 1][0] = dist + 1
pq.append((other, dist + 1))
# 第二次到达
elif explored[other - 1][0] < dist + 1 < explored[other - 1][1]:
explored[other - 1][1] = dist + 1
if other == n:
break
pq.append((other, dist + 1))
ans = 0
for i in range(explored[-1][1]):
ans += time
if i < explored[-1][1] - 1 and (ans // change) % 2:
ans = (ans + change) // change * change
return ans
Java实现
class Solution {
private static final int INF = 0x3f3f3f3f;
public int secondMinimum(int n, int[][] edges, int time, int change) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for(int[] edge: edges){
List<Integer> a = graph.getOrDefault(edge[0] - 1, new ArrayList<>());
List<Integer> b = graph.getOrDefault(edge[1] - 1, new ArrayList<>());
a.add(edge[1] - 1);
b.add(edge[0] - 1);
graph.put(edge[0] - 1, a);
graph.put(edge[1] - 1, b);
}
int[][] explored = new int[n][2];
for(int i=0;i<n;i++)
Arrays.fill(explored[i], INF);
Deque<int[]> queue = new ArrayDeque<>();
queue.addLast(new int[]{0, 0});
explored[0][0] = 0;
while(!queue.isEmpty()){
int[] cur = queue.pollFirst();
int idx = cur[0], nxtDist = cur[1] + 1;
for(int other: graph.get(idx)){
if(nxtDist < explored[other][0])
explored[other][0] = nxtDist;
else if(nxtDist > explored[other][0] && nxtDist < explored[other][1]){
explored[other][1] = nxtDist;
if(other == n - 1)
break;
}
else
continue;
queue.addLast(new int[]{other, nxtDist});
}
}
int ans = 0;
for(int i=0;i<explored[n-1][1];i++){
ans += time;
if(i < explored[n-1][1] - 1 && (ans / change) % 2 == 1)
ans = (ans + change) / change * change;
}
return ans;
}
}