## https://yukicoder.me/problems/no/614 import heapq def main(): N, M, K, S, T = map(int, input().split()) abc = [] for _ in range(M): a, b, c = map(int, input().split()) abc.append((a - 1, b, c)) map_array = [[] for _ in range(N)] for a, b, c in abc: map_array[a].append(b) map_array[a + 1].append(c) map_array[0].append(S) map_array[-1].append(T) coord_map_array = [{} for _ in range(N)] for i, values in enumerate(map_array): values.sort() for j, value in enumerate(values): coord_map_array[i][value] = j # グラフ構築 next_nodes = [{} for _ in range(N)] for a, b, c in abc: b_i = coord_map_array[a][b] c_i = coord_map_array[a + 1][c] if b_i not in next_nodes[a]: next_nodes[a][b_i] = [] next_nodes[a][b_i].append((a + 1, c_i, 0)) for i, values in enumerate(map_array): if len(values) == 0: continue for j in range(len(values) - 1): a = values[j] b = values[j + 1] if j not in next_nodes[i]: next_nodes[i][j] = [] if (j + 1) not in next_nodes[i]: next_nodes[i][j + 1] = [] next_nodes[i][j].append((i, j + 1, b - a)) next_nodes[i][j + 1].append((i, j, b - a)) # ダイクストラ法で解く s_ = coord_map_array[0][S] t_ = coord_map_array[-1][T] fix = {} seen = {(0, s_):0} queue = [] heapq.heappush(queue, (0, 0, s_)) while len(queue) > 0: cost, a, k = heapq.heappop(queue) if (a, k) in fix: continue fix[(a, k)] = cost if k not in next_nodes[a]: continue for b, c, d in next_nodes[a][k]: if (b, c) in fix: continue new_cost = cost + d if (b, c) not in seen or seen[(b, c)] > new_cost: seen[(b, c)] = new_cost heapq.heappush(queue, (new_cost, b, c)) if (N - 1, t_) not in fix: print(-1) else: print(fix[(N -1 , t_)]) if __name__ == "__main__": main()