Exemplo n.º 1
0
	Paths* popPathFrom(string c) {
		Paths* ps = getPathFrom(c);
		for(int i=0;i<ps->size();i++) {
			this->remove(ps->at(i));
		}
		return ps;
	}
Exemplo n.º 2
0
int main(int argc, char** argv)  {

	int n, m;
	int val;
	string c, c1, c2;

	// initialize & input
	cin>>n>>m;
	Citys citys(n);
	Paths paths;
	SpanningPaths spanning_path;

	for(int i=0;i<n;i++) {
		cin >> c;
		citys.setName(i, c);
	}

	for(int i=0;i<m;i++) {
		cin>>c1>>c2>>val;
		paths.push(new Path(c1, c2, val));
	}

	// kruskal's algo
	paths.sortByCost();
	for (int i=0; i<paths.size(); i++) {
		Path* p = paths.at(i);
		if (!spanning_path.existRingIfAdd(p)) {
			spanning_path.push(p->clone());
		}
	}

	int total_cost = 0;
	for (int i=0; i<spanning_path.size(); i++) {
		Path* p = spanning_path.at(i);
		cout << "(" << p->c1 << " " << p->c2 << ") ";
		total_cost += p->cost;
	}
	cout << "\n" << total_cost << endl;

//	paths.list();
//	spanning_path.list();

	return 0;
}
Exemplo n.º 3
0
	bool existRingIfAdd(Path* p) {
		if (this->size() == 0) {
			return false;
		}

		Paths *tmp_path = this->clone();
		string t;

		// BFS
		vector<string> sv, ev;
		sv.push_back(p->c1);
		sv.push_back(p->c2);
		while ( !sv.empty() ) {
			t = sv.back();
			sv.pop_back();
			if ( std::find(ev.begin(), ev.end(), t) != ev.end() ) {
				delete tmp_path;
				return true;
			} else {
				ev.push_back(t);
				Paths* ps = tmp_path->popPathFrom(t);
				for (int i=0;i<ps->size();i++) {
					Path* p = ps->at(i);
					if (p->c1 == t) {
						sv.push_back(p->c2);
					} else {
						sv.push_back(p->c1);
					}
				}
				delete ps;
			}
		}
		delete tmp_path;

		return false;
	}