#include #include #include "citytable.h" #include "intmatrix.h" using namespace std; citytable * read_cities(string fname) { ifstream fin(fname.c_str()); if (fin.fail()) { cerr << "Can't read file '" << fname << "'\n"; exit(1); } citytable * C = new citytable(); while (true) { string name1, name2, roadname; int length; fin >> name1 >> name2 >> roadname >> length; if (fin.fail()) break; int p = C->get_index(name1); if (p == -1) { p = C->add(name1); cout << name1 << " is city number " << p << "\n"; } p = C->get_index(name2); if (p == -1) { p = C->add(name2); cout << name2 << " is city number " << p << "\n"; } } fin.close(); return C; } void read_lengths(string fname, citytable * C, intmatrix * M) { ifstream fin(fname.c_str()); if (fin.fail()) { cerr << "Can't read file '" << fname << "'\n"; exit(1); } while (true) { string name1, name2, roadname; int length; fin >> name1 >> name2 >> roadname >> length; if (fin.fail()) break; int p1 = C->get_index(name1); int p2 = C->get_index(name2); M->set(p1, p2, length); M->set(p2, p1, length); } fin.close(); } intmatrix * next_step(int intermed, intmatrix * prev) { int rows = prev->get_rows(), cols = prev->get_columns(); intmatrix * next = new intmatrix(rows, cols); for (int r = 0; r < rows; r += 1) for (int c = 0; c < cols; c += 1) { int old_dist = prev->get(r, c); int new_dist = -1; int new_dist_a = prev->get(r, intermed); int new_dist_b = prev->get(intermed, c); if (new_dist_a != -1 && new_dist_b != -1) new_dist = new_dist_a + new_dist_b; if (old_dist == -1 || new_dist != -1 && new_dist < old_dist) next->set(r, c, new_dist); else next->set(r, c, old_dist); } return next; } int main(int argc, char * argv[]) { if (argc < 2) { cerr << "map file name reuqired on command line\n"; exit(1); } citytable * C = read_cities(argv[1]); int N = C->get_number(); intmatrix * D = new intmatrix(N, N); D->fill(-1); for (int i = 0; i < N; i += 1) D->set(i, i, 0); read_lengths(argv[1], C, D); D->print(); cout << "\n"; for (int step = 0; step < N; step += 1) { D = next_step(step, D); cout << "----- " << step << " -----\n"; D->print(); } cout << "\n\nFINALLY:\n"; C->print(); D->print(); }