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 ;}