#include "CityConnector.h" CityConnector::CityConnector(string InputFileName) { cityID = 0; LoadPairs(InputFileName.c_str() ); initialized = true; } CityConnector::CityConnector(void) { initialized = false; cityID = 0; } void CityConnector::LoadFile(const char * filename) { LoadPairs(filename); initialized = true; } void CityConnector::ReportConnectedCities() { if(!initialized) { cout << "CityConnector is not initialized(no file loaded)... Exiting..." << endl; system("pause"); exit(-1); } UnionConnections(); Print(); } bool CityConnector::CheckConnection(string city_1, string city_2) { if(!initialized) { cout << "CityConnector is not initialized(no file loaded)... Exiting..." << endl; system("pause"); exit(-1); } int c1 = city2int[city_1]; int c2 = city2int[city_2]; c1 = djs.Find(c1); c2 = djs.Find(c2); if(c1 == c2) { cout << "YES" << endl; return 1; } cout << "NO" << endl; return 0; } void CityConnector::LoadPairs(const char *filename) { ifstream istream; string line, city1, city2; int pos; istream.open(filename, ios_base::in); if(!istream) { cout << "Error opening file: " << filename << endl; system("pause"); exit(0); } while (!istream.eof()) { //get string getline(istream, line); //split string pos = line.find(','); city1 = line.substr(0, pos); city2 = line.substr(pos+2); //If the cities isn't in our maps... map them map::iterator it = city2int.find(city1); if (it == city2int.end()) { city2int.insert(make_pair(city1, cityID) ); int2city.insert(make_pair(cityID++, city1) ); } it = city2int.find(city2); if (it == city2int.end()) { city2int.insert(make_pair(city2, cityID) ); int2city.insert(make_pair(cityID++, city2) ); } //store the connection connections.push_back( make_pair(city1, city2) ); } istream.close(); //Make union-find(disjoint-sets) structure with size of our elements //and set them all in their own equivalence class (setting each to -1) djs.Init(cityID); } void CityConnector::UnionConnections(void) { if(!initialized) { cout << "CityConnector is not initialized(no file loaded)... Exiting..." << endl; system("pause"); exit(-1); } vector >::iterator it; for (it = connections.begin(); it != connections.end(); ++it) { int first, second; first = city2int[it->first]; second = city2int[it->second]; djs.Union(first, second); } } void CityConnector::Print(void) { if(!initialized) { cout << "CityConnector is not initialized(no file loaded)... Exiting..." << endl; system("pause"); exit(-1); } string heading = "Equivalence Class #"; //Load final node to root mapping for each node for(unsigned int i = 0; i::iterator, hash_multimap::iterator> itPair; //get all nodes with root i itPair = node2root.equal_range(i); //print heading cout << endl << heading << headingNum++ << endl << endl; //print every city attatched to root i, including i hash_multimap::iterator iter; for(iter = itPair.first; iter != itPair.second; ++iter) { cout << int2city[iter->second] << endl; } } } }