poj3259 (SPFA)

Source: Internet
Author: User

Own first SPFA, commemorate a bit, by the way reprint SPFA principle. First PO Code:

#include <iostream>#include<queue>using namespacestd;Const intMAX =999999;Const intMAXN =501;intMinimumintAintb) {    returna > B?b:a;}intMain () {intT; CIN>>T;  while(t--){        intN, M, W; CIN>> n >> M >>W; intFIELD[MAXN]; BOOLVISITED[MAXN]; intEDGE[MAXN][MAXN]; intVISITCNT[MAXN]; memset (field, MAX,sizeof(field)); Memset (Edge, MAX,sizeof(Edge)); Memset (visited,0,sizeof(visited)); memset (visitcnt,0,sizeof(visitcnt));  for(inti =0; I < m; i++){            intfield1, Field2, Len; CIN>> field1 >> field2 >>Len; EDGE[FIELD1][FIELD2]=minimum (edge[field1][field2], Len); Edge[field2][field1]=minimum (Edge[field2][field1], Len); }         for(inti =0; i < W; i++){            intfield1, Field2, Len; CIN>> field1 >> field2 >>Len; EDGE[FIELD1][FIELD2]= Minimum (Edge[field1][field2], (-1) *Len); } field[1] =0; Queue<int>Q; Q.push (1); visited[1] =true; visitcnt[1] =1; BOOLFlag =false;  while(!Q.empty ()) {            intCurrent =Q.front ();            Q.pop (); Visited[current]=false;  for(inti =1; I <= N; i++){                intTMP = Field[current] +Edge[current][i]; if(TMP <Field[i]) {Field[i]=tmp; if(!Visited[i])                        {Q.push (i); Visited[i]=true; Visitcnt[i]++; if(Visitcnt[i] >N) {Flag=true;  Break; }                    }                }            }            if(flag) Break; }        if(flag) {cout<<"YES"<<Endl; }        Else{cout<<"NO"<<Endl; }    }    return 0;}

The following is transferred from http://www.cnblogs.com/zgmf_x20a/archive/2008/12/18/1357737.html

The shortest path algorithm has many kinds, besides the sort, I am afraid it is the most in the Oi field solving the same kind of problem algorithm. The most familiar is undoubtedly the Dijkstra, followed by the Bellman-ford, they can find the shortest path from one source point to the other; if we want to ask for the shortest path between each pair of vertices, we can also use Floyd-warshall.

SPFA is an algorithm for this log to be written, its performance is very good, the code implementation is not complicated. Especially when the scale of the graph is large, when the adjacency matrix cannot be used, the SPFA can be easily confronted with the pro-connection table. Everyone has written a wide search, the implementation of SPFA and wide search very similar.

How to find the shortest path length value?

First of all, SPFA is a single-source shortest path algorithm, so the following "the shortest path length of a point" refers to "the shortest path length of a point to the source point".

We remember that the source point is S, the "Current shortest path" from the source point to point I is d[i], starting with all D[i] initialized to infinity, D[s] is initialized to 0. What the algorithm does is to try to reduce the elements of the d[] array in the process of running, eventually reducing each of these elements to the actual shortest path.

Process, we maintain a queue, start by placing the source point on the team head, and then repeat the operation until the queue is empty:

(1) from the first team to take out a node u, scanning all the nodes can be reached by the U node, the specific scanning process, with the different storage mode;

(2) Once such a node is found, which is recorded as V, satisfies d[v] > D[u] + w (u, v), the value of d[v] is reduced to equal to D[u] + w (u, v). where W (u, v) is the length of the edge u-v in the figure, because the u-v must be adjacent, so this length must be known (otherwise we will not get a complete picture); This operation is called relaxation.

The principle of relaxation operation is the famous theorem: "The sum of the two sides of the triangle is greater than the third side", in the informatics we call it triangular inequalities. The so-called i,j relaxation, is to determine whether D[J]&GT;D[I]+W[I,J], if the formula is set to D[J] reduced to d[i]+w[i,j], or not move.


(3) In the previous step, we thought that we "improved" the shortest path of node V, the current path length of Node V D[v] was reduced compared to the previous one, so the path length of some nodes connected to V may be reduced correspondingly. Note that it is possible, not necessarily. But even so, we still need to add V to the queue to wait for processing, to ensure that the path value of these nodes at the end of the algorithm is reduced to optimal. Of course, if the connection to the side of the V is more, the algorithm runs, the path length of the node v may be improved several times, if we therefore put V into the queue multiple times, the subsequent work is undoubtedly redundant. In this way, we need to maintain a bool array inqueue[] to record whether each node is already in the queue. We only join the queue for points that have not yet joined the queue.


can the algorithm end?

For graphs that do not have a negative weight loop, the above algorithm is bound to end. Because the algorithm in the iterative optimization of the shortest path length, there will always be a moment to enter the "can not optimize" the situation, when the queue read empty, the algorithm is over. However, if there is a loop with a negative weight in the graph, it is bad that the algorithm runs repeatedly on it, and endlessly attempts to reduce the shortest path value of some related points by "circling". If we cannot guarantee that there is no negative power loop in the chart, an "end condition" is necessary. What is the end condition?

Thinking about the Bellman-ford algorithm, how did it end? Obviously, the simplest bellman-ford algorithm, no matter what happens in the loop, loops | V|-1 to end. Intuitively we can feel that the SPFA algorithm is "smarter", which means we can guess if, in SPFA, a point goes into the queue-or a point is processed-more than | v| times, then it can be concluded that there is a negative power loop in the diagram.


How does the shortest path itself output?

In a picture, we only know that the shortest path length of Node A to node E is 73, sometimes with little meaning. If this drawing is a map model, after calculating the shortest path length, we always have to explain "how to go" to really solve the problem. How to record the shortest path in the process of calculation, and at the end of the output it?

Path[] Array, Path[i] represents the number of nodes before node I in the shortest path from S to I. Note that it is "before", not "after". The core idea of the shortest path algorithm becomes "slack", the principle is triangle inequality, the method is mentioned above. We only need to use the junction u to relax the node v at the same time, labeled path[v] = u, the recorded work is done.

Output may encounter a bit of difficulty, we remember that each point "front" point is what, the output is to go from the front to the last side of the loss, this is not easy to do. Actually very good, see the following recursive method:

void Printpath (int k) {
if (Path[k]) Printpath (path[k]);
fout<<k<< ";
}

poj3259 (SPFA)

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.