Heat Wave

Interview

Time limit1sMemory limit128 MB

Summary
Given an undirected weighted graph, find the minimum total cost of a route from a source town to a destination town.
Level

Medium4 of 10

Topics
Graph, Shortest path, Heap, Greedy
Solved
No attempts yet

Problem

Texas is suffering a heat wave this summer. Farmer John is in charge of delivering plenty of ice-cold milk from Wisconsin to Texas so the Texans can beat the heat.

The routes that can carry the milk pass through a total of TT towns, numbered 11 through TT (including the starting and ending towns). Each road connects two towns bidirectionally and has a traversal cost (gasoline, tolls, and so on).

Below is an example map of seven towns. Town 55 is the source of the milk and town 44 is its destination; the bracketed integers are the traversal costs.

                              [1]----1---[3]-
                             /               \
                      [3]---6---[4]---3--[3]--4
                     /               /       /|
                    5         --[3]--  --[2]- |
                     \       /        /       |
                      [5]---7---[2]--2---[3]---
                            |       /
                           [1]------

For example, traversing 5→6→3→45 \to 6 \to 3 \to 4 costs 3+4+3=103 + 4 + 3 = 10.

Given all CC roads (each described by its two endpoints R1iR1_i, R2iR2_i and cost CiC_i), find the smallest total cost to travel from the starting town TsT_s to the destination town TeT_e.

Constraints: 1≤T≤25001 \le T \le 2500, 1≤C≤62001 \le C \le 6200, 1≤R1i,R2i≤T1 \le R1_i, R2_i \le T, 1≤Ci≤10001 \le C_i \le 1000, 1≤Ts,Te≤T1 \le T_s, T_e \le T.

Input

  • Line 1: Four space-separated integers TT, CC, TsT_s, and TeT_e.
  • Lines 22 through C+1C+1: Line i+1i+1 describes road ii with three space-separated integers R1iR1_i, R2iR2_i, and CiC_i.

Output

  • Line 1: A single integer, the total cost of the shortest route from TsT_s to TeT_e. At least one route is guaranteed to exist.

Hint

In the sample input, the shortest route is 5→6→1→45 \to 6 \to 1 \to 4 with cost 3+1+3=73 + 1 + 3 = 7.

Examples3

  1. Example 1

    Input
    7 11 5 4
    2 4 2
    1 4 3
    7 2 2
    3 4 3
    5 7 5
    7 3 3
    6 1 1
    6 3 4
    2 4 3
    5 6 3
    7 2 1
    
    Expected output
    7
    
  2. Example 2

    Input
    2 1 1 2
    1 2 7
    
    Expected output
    7
    
  3. Example 3

    Input
    3 3 1 3
    1 2 1
    2 3 1
    1 3 5
    
    Expected output
    2