UVA_10048_Audiophobia

#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]++;
			}
		}
	}
};
class Edge
{
public:
	pair<int,int>vertex;
	int weight;
};
bool compare(const Edge&a, const Edge&b)
{
	if (a.weight != b.weight)
	{
		return a.weight < b.weight;
	}
	if (a.vertex.first != b.vertex.first)
	{
		return a.vertex.first < b.vertex.first;
	}
	return a.vertex.second < b.vertex.second;
}
vector<Edge>getEdge(const int &m)
{
	vector<Edge>edge(m);
	for (int i = 0; i < m; i++)
	{
		cin >> edge[i].vertex.first >> edge[i].vertex.second >> edge[i].weight;
		edge[i].vertex.first--;
		edge[i].vertex.second--;
	}
	sort(edge.begin(), edge.end(), compare);
	return edge;
}
int kruscal(const int &n,const vector<Edge>&edge)
{
	int first, second; cin >> first >> second;
	first--;second--;
	DisjoinSet union_set(n);
	for (size_t i = 0; i < edge.size(); i++)
	{
		if (union_set.find(edge[i].vertex.first) != union_set.find(edge[i].vertex.second))
		{
			union_set.merge(edge[i].vertex.first, edge[i].vertex.second);
			if (union_set.find(first) == union_set.find(second))
			{
				return edge[i].weight;
			}
		}
	}
	return 0;
}
int main()
{
	//freopen("input.txt","r",stdin);  
	//freopen("output.txt","w",stdout);
	int n, m, q,count=0;
	bool flag = false;
	while (cin >> n >> m >> q)
	{
		if (!n&&!m&&!q)
		{
			break;
		}
		if (flag)
		{
			cout << endl;
		}
		else
		{
			flag = true;
		}
		printf("Case #%d\n",++count);
		auto edge = getEdge(m);
		while (q--)
		{
			auto result = kruscal(n, edge);
			if (result)
			{
				cout << result << endl;
			}
			else
			{
				cout << "no path" << endl;
			}
		}
	}
	return 0;
}

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