Spfa algorithm Template

Source: Internet
Author: User
Const maxp = 10000; {maximum number of knots} var P, C, S, T: longint; {P, number of knots; C, number of edges; s: start point; t: destination} A, B: array [1 .. maxp, 0 .. maxp] of longint; {A [x, y] stores the right of the edge between x and y; B [x, c] store another node of the Side C connected to x, y} D: array [1 .. maxp] of integer; {queue} V: array [1 .. maxp] of Boolean; {indicates whether to join the queue} Dist: array [1 .. maxp] of longint; {the shortest path from the start} head, tail: longint; {head/tail pointer} procedure Init; var I, x, y, z: longint; begin read (p, c); for I: = 1 to C do begin readln (x, y, z); {X, Y: two nodes of an edge; Z: the weight of this edge} Inc (B [x, 0]); B [X, B [x, 0]: = y; A [x, y]: = z; {B [x, 0]: Number of edges with X as a node} Inc (B [y, 0]); B [y, B [y, B [y, 0]: = x; A [y, X]: = z; end; readln (S, T); {read start and end} end; Procedure spfa (s: longint); {spfa} var I, j, now, sum: longint; begin fillchar (D, sizeof (D), 0); fillchar (v, sizeof (V ), false); For J: = 1 to P do Dist [J]: = maxlongint; Dist [s]: = 0; V [s]: = true; d [1]: = s; {initial status of the queue, s as the starting point} head: = 1; tail: = 1; while head <= tail do {the queue is not empty} begin now: = d [head]; {first element} For I: = 1 to B [now, 0] Do if Dist [B [now, i]> Dist [now] + A [now, B [now, I] Then begin Dist [B [now, I]: = DIST [now] + A [now, B [now, I]; {change the Shortest Path} if not V [B [now, i] Then {extended node into the queue} begin Inc (tail); D [tail]: = B [now, I]; V [B [now, I]: = true; end; V [now]: = false; {release node} Inc (head); {team} end; Procedure print; begin writeln (Dist [T]); end; begin Init; spfa (s); print; end.

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.