This topic mainly uses string-to-integer ing and naturally comes to mind the map in STL. Ah, it has contributed countless times to WA, at last, we found that map had forgotten to be cleared every time it was run !!!! In this question, both dijkstra and spfa can be used, but remember to use C ++ for submission. G ++ may time out. This topic is an undirected graph. When the departure station and the terminal station are both output 0 !! I can use dijkstra and spfa. Please refer to the Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <string> # include <algorithm> # include <queue> # include <cmath> # include <map> using namespace std; const int MAXN = 1005; const int INF = 0x7fffffff; struct Node {int adj; int dist; Node * next ;}; int cnt; Node * vert [MAXN]; // create the vertex header pointer array int vis [MAXN]; int dis [MAXN]; // create the distance array map <string, int> mymap; void dijkstra (int v0) {int I; for (I = 1; I <= Cnt; I ++) {dis [I] = INF;} dis [v0] = 0; vis [v0] = 1; int min = INF; int u = v0; Node * p; for (I = 1; I <= cnt-1; I ++) {p = vert [u]; while (p! = NULL) {int ty = p-> adj; int td = p-> dist; if (! Vis [ty] & dis [u] + td <= dis [ty]) {dis [ty] = dis [u] + td ;} p = p-> next;} int j; min = INF; for (j = 1; j <= cnt; j ++) {if (! Vis [j] & dis [j] <min) {u = j; min = dis [j] ;}} vis [u] = 1 ;}} queue <int> mq; int inq [MAXN]; void spfa (int v0) {memset (inq, 0, sizeof (inq); while (! Mq. empty () // clear mq queues. pop (); mq. push (v0); inq [v0] ++; int tmp; Node * p; int I; for (I = 1; I <= cnt; I ++) {dis [I] = INF;} dis [v0] = 0; while (! Mq. empty () {tmp = mq. front (); mq. pop (); inq [tmp] --; p = vert [tmp]; while (p! = NULL) {int tadj = p-> adj; int td = p-> dist; int tk; tk = dis [tmp] + td; if (dis [tmp] <INF & tk <dis [tadj]) {dis [tadj] = tk; if (inq [tadj] = 0) {mq. push (tadj); inq [tadj] ++ ;}} p = p-> next ;}} int main () {int n; while (scanf ("% d", & n )! = EOF) {if (n =-1) break; memset (vis, 0, sizeof (vis); memset (vert, 0, sizeof (vert); mymap. clear (); // never forget to clear the map !! Cnt = 0; string s1, s2; cin> s1; mymap [s1] = ++ cnt; cin> s2; int pan = 0; if (s1 = s2) {pan = 1;} else mymap [s2] = ++ cnt; int I; for (I = 0; I <n; I ++) {string st1; string st2; int d; cin> st1> st2> d; if (mymap. find (st1) = mymap. end () {mymap [st1] = ++ cnt;} if (mymap. find (st2) = mymap. end () {mymap [st2] = ++ cnt;} int t1, t2; t1 = mymap [st1]; t2 = mymap [st2]; Node * p; p = new Node; // create an adjacent table p-> adj = t2; p-> dist = d; p-> next = vert [t1]; vert [t1] = p; p = new Node; p-> adj = t1; p-> dist = d; p-> next = vert [t2]; vert [t2] = p;} if (pan = 1) {printf ("0 \ n"); continue;} // dijkstra (1); spfa (1 ); if (dis [2] <INF) {printf ("% d \ n", dis [2]);} else {printf ("-1 \ n ");}} return 0 ;}