UVA_544_Heavy Cargo

#include<iostream>  
#include<sstream>  
#include<string>  
#include<vector>  
#include<list>  
#include<set>  
#include<map>  
#include<stack>  
#include<queue>  
#include<algorithm>  
#include<cmath>  
#pragma warning(disable:4996)  
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::sort;
class DisjoinSet
{
private:
	vector<int>represent, rank;
public:
	DisjoinSet(const int &n) :represent(n), rank(n)
	{
		for (int i = 0; i < n; i++)
		{
			represent[i] = i;
		}
	}
	int find(int i)
	{
		return represent[i] = represent[i] == i ? i : find(represent[i]);
	}
	void merge(const int &x, const int &y)
	{
		auto a = find(x); auto b = find(y);
		if (rank[a] < rank[b])
		{
			represent[a] = b;
		}
		else
		{
			represent[b] = a;
			if (rank[b] == rank[a])
			{
				rank[a]++;
			}
		}
	}
};
typedef struct
{
	pair<string, string>vertex_city;
	pair<int, int>vertex_number;
	int weight;
}Edge;
bool compare(const Edge&a, const Edge&b)
{
	if (a.weight != b.weight)
	{
		return a.weight > b.weight;
	}
	if (a.vertex_city.first != b.vertex_city.second)
	{
		return a.vertex_city.first < b.vertex_city.first;
	}
	return a.vertex_city.second < b.vertex_city.second;
}
vector<Edge>getEdge()
{
	int n, m;
	cin >> n >> m;
	if (!n&&!m)
	{
		exit(0);
	}
	vector<Edge>edge(m);
	for (int i = 0; i < m; i++)
	{
		cin >> edge[i].vertex_city.first >> edge[i].vertex_city.second >> edge[i].weight;
	}
	sort(edge.begin(), edge.end(), compare);
	return edge;
}
int kruscal(vector<Edge>&edge)
{
	map<string, int>Map;
	for (size_t i = 0; i < edge.size(); i++)
	{
		Map.insert({ edge[i].vertex_city.first,0 });
		Map.insert({ edge[i].vertex_city.second,0 });
	}
	int i = 0;
	for (auto iter = Map.begin(); iter != Map.end(); iter++)
	{
		iter->second = i++;
	}
	for (size_t i = 0; i < edge.size(); i++)
	{
		edge[i].vertex_number.first = Map[edge[i].vertex_city.first];
		edge[i].vertex_number.second = Map[edge[i].vertex_city.second];
	}
	string initial_city, terminal_city; cin >> initial_city >> terminal_city;
	auto initial_number = Map[initial_city]; auto terminal_number = Map[terminal_city];
	DisjoinSet union_set(Map.size());
	for (size_t i = 0;i<edge.size();i++)
	{
		if (union_set.find(edge[i].vertex_number.first) != union_set.find(edge[i].vertex_number.second))
		{
			union_set.merge(edge[i].vertex_number.first, edge[i].vertex_number.second);
			if (union_set.find(initial_number) == union_set.find(terminal_number))
			{
				return edge[i].weight;
			}
		}
	}
	return 0;
}
int main()
{
	//freopen("input.txt","r",stdin);  
	//freopen("output.txt","w",stdout);
	int count = 0;
	while (1)
	{
		auto edge = getEdge();
		printf("Scenario #%d\n%d tons\n\n", ++count, kruscal(edge));
	}
	return 0;
}

你可能感兴趣的:(uva,kruscal,union_find)