Poj 1502 MPI Maelstrom SPFA optimized by queue

Source: Internet
Author: User

Question Link

The typical problem of finding the shortest path is solved from the node 1 ~~

Find the shortest path from 1.

# Include <stdio. h> # include <iostream> # include <string. h> # include <string> # include <map> # include <vector> # include <math. h> # include <queue> # include <stdlib. h> # define maxn 1000 # define INF 100000000 using namespace std; vector <pair <int, int> g [maxn + 10]; char ch [10000], ans [100]; int node, edge, src; int dis [maxn + 10]; bool inQueue [maxn + 10]; queue <int> que; pair <int, int> suit; void SPFA () {for (int I = 0; I <= node; I ++) dis [I] = INF; memset (inQueue, false, sizeof (int) * (node + 5); dis [src] = 0; while (! Que. empty () {que. pop ();} que. push (src); inQueue [src] = true; while (! Que. empty () {int u = que. front (); que. pop (); for (int I = 0; I! = G [u]. size (); I ++) {if (dis [u] + g [u] [I]. second <dis [g [u] [I]. first]) {// enter the distance from u. // Printf (": % d \ n", u, g [u] [I]. first); // printf (": % d \ n", dis [u], g [u] [I]. second); dis [g [u] [I]. first] = dis [u] + g [u] [I]. second; // printf (": % d \ n", dis [g [u] [I]. first]); // printf (": % d \ n", u, g [u] [I]. first); if (! InQueue [g [u] [I]. first]) {inQueue [g [u] [I]. first] = true; que. push (g [u] [I]. first) ;}} inQueue [u] = false ;}} int main () {while (scanf ("% d", & node )! = EOF) {getchar (); for (int I = 2; I <= node; I ++) {gets (ch); int add, ji = 1; char * p = ch; while (sscanf (p, "% s % n", ans, & add )! = EOF) {if (ans [0] = 'X') {ji ++; p = p + add; continue ;} // note that the value of ji ++ is missing, which leads to an error in updating the adjacent list. Suit. second = atoi (ans); suit. first = ji; g [I]. push_back (suit); suit. first = I; g [ji]. push_back (suit); p = p + add; ji ++ ;}} src = 1; SPFA (); int max =-1; for (int I = 1; I <= node; I ++) {if (max <dis [I]) max = dis [I];} printf ("% d \ n", max );} return 0 ;}

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.