"Programming Marathon" "016-Home for the New Year"

Source: Internet
Author: User

"Programming Marathon algorithm Directory" "016-Chinese New Year Home" "Project download >>>" 1 Topic Description

Nowcoder bought a new car this year, he decided to drive home for the Spring Festival. Go home in the process to go through the N-size toll station, the cost of each toll station is different,
Can you help him to calculate the minimum cost of tolls?

1.1 Input Description:

The input contains more than one set of data, the first row of each group of data contains two positive integers m (1≤m≤500) and N (1≤n≤30), where n means there are n toll stations,
The numbers are 1, 2 、...、 N, in turn. The departure number is 0 and the end number is N, which requires 0 to n.
Immediately following M-line, each line contains three integers F, T, C, (0≤f, t≤n; 1≤C≤10), respectively, from the place numbered F to the T, need to pay C yuan tolls.

1.2 Output Description:

For each set of data, please output at least how many tolls you need to pay.

1.3 Input Example:
8 40 1 100 2 51 2 21 3 12 1 32 3 92 4 23 4 4
1.4 Output Example:
7
2 ideas for solving problems

According to test instructions, it is possible to construct a direction graph based on the input, where the origin and toll stations represent the vertices of the graph, and the tolls indicate the weights of the edges. The minimum charge required for departure to the end point is equivalent to finding the starting and ending points to a short path, which can be processed using the Dijkstra algorithm.

2.1 Dijkstra Algorithm 2.1.1 Definition Overview

The Dijkstra (Dijkstra) algorithm is a typical single-source shortest path algorithm that calculates the shortest path of a node to all other nodes. The main feature is to extend from the center of the starting point to the outer layer until it expands to the end point. Dijkstra algorithm is a very representative shortest path algorithm, in many professional courses as the basic content of the detailed introduction, such as data structure, graph theory, operations research and so on. Note that the algorithm requires no negative weight edges in the graph.
Problem Description: In no (have) to Figure g= (v,e), assuming that each edge e[i] length is w[i], find the shortest path from vertex v_0 to the remaining points. (Single source Shortest path)

2.1.2 Algorithm Description

  1) algorithm idea:
Set g= (v,e) is a weighted graph, the vertex set V in the graph is divided into two groups, the first set is the vertex set of the shortest path has been found (in s), there is only one source point in the initial S, and each time a shortest path is obtained, it will be added to the set S, until all the vertices are added to S, the algorithm is ended), The second set is the set of vertices of the remaining indeterminate shortest path (denoted by u), and the second group of vertices is added in the order of the shortest path length in the S. During the join process, the shortest path length that is always maintained from the source Point V to the vertices in S is not longer than the shortest path length from the source point V to any vertex in U. In addition, each vertex corresponds to a distance, the distance from the vertex in S is the shortest path length from V to the vertex, and the distance from the vertex in U is the current shortest path length from V to the vertex that includes only the vertex in S as the middle vertex.
  2) algorithm steps:
A) Initially, S contains only the source point, that is, the distance of S={v},v is 0. U contains other vertices other than V, that is: u={remaining vertices}, if V and u in vertex u have edges, then <u,v> normal right value, if U is not V's out edge adjacency point, then <u,v> weight is ∞.
b) Select a minimum distance v from u k, add K, join S (the selected distance is the shortest path length of V to K).
c) Change the distance of each vertex in the U with K as the new consideration; If the distance from the source point v to the vertex u (through vertex K) is shorter than the original distance (without the vertex K), the distance value of the vertex U is modified, the distance of the vertex k of the modified distance value plus the right edge.
D) Repeat steps b and c until all vertices are contained in S.

2.1.3 Illustrative Examples

Construct a graph based on the input of the example, and then use the Dijkstra algorithm to find the shortest path, as shown in construction 1 of the path.

Figure 1 Dijkstra Construction Shortest Path

3 Algorithm Implementation
ImportJava.util.Scanner;/** * Author: Wang Junshu * time:2016-05-11 19:56 * CSDN:HTTP://BLOG.CSDN.NET/DERRANTCM * github:https://github.com/wang-ju N-chao * declaration:all rights Reserved!!! */ Public  class Main {     Public Static void Main(string[] args) {Scanner Scanner =NewScanner (system.in);//Scanner Scanner = new Scanner (Main.class.getClassLoader (). getResourceAsStream ("Data.txt"));         while(Scanner.hasnext ()) {intline = Scanner.nextint ();number of//toll stations plus starting point            intnum = scanner.nextint () +1;int[] Graph =New int[Num] [Num];//initialization diagram             for(inti =0; i < num; i++) { for(intj =0; J < num; J + +) {if(I! = j)                    {Graph[i][j] = Integer.max_value; }                }            }//Read input construct to graph             for(inti =0; I < line; i++) {intx = Scanner.nextint ();inty = Scanner.nextint ();intv = scanner.nextint ();            Graph[x][y] = v;        } System.out.println (Dijkstra (graph));    } scanner.close (); }/** * The starting point is 0, the end point is the shortest path of graph.length-1, the weight can not be negative * * @param Graph graph * @return Shortest path, no return     Back to Integer.max_value; */    Private Static int Dijkstra(int[] graph) {//Mark whether vertices have been visited        Boolean[] S =New Boolean[Graph.length];//Record the shortest distance from the starting point to each point        int[] DIST =New int[Graph.length];//Record the precursor vertex and find the shortest path from (V, W) by finding the precursor .        int[] PREV =New int[Graph.length];//processing the first point         for(inti =0; i < graph.length; i++) {Dist[i] = graph[0][i];//If it is the maximum value, the description (0, i) does not exist. So prev[i] does not exist            if(Dist[i] = = Integer.max_value) {Prev[i] =-1; }Else{Prev[i] =0; }        }//Mark number No. 0 vertex has been processeds[0] =true;//Handle the remaining points         for(inti =1; i < s.length; i++) {intmin = Integer.max_value;intU =0;//Find the unreachable vertex J, and the value of Dist[j] is minimized             for(intj =0; J < S.length; J + +) {if(!                    S[J] && Dist[j] < min) {u = j;                min = Dist[j]; }            }//Mark U has been visitedS[u] =true; for(intj =0; J < S.length; J + +) {//J has not been visited, and (U, j) up to                if(! S[J] && Graph[u][j] < Integer.max_value) {intv = dist[u] + graph[u][j];//from 0->...->u->j shorter than 0->...->j (other path)                    if(v < dist[j]) {Dist[j] = V;//J is accessible via UPREV[J] = u; }                }            }        }returnDist[dist.length-1]; }}
4 Test Results

5 Other information

Because Markddow is not good for editing, uploading a picture of a document for reading. PDF and Word documents can be "downloaded >>>" on GitHub.

"Programming Marathon" "016-Home for the New Year"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.