DU-1598-find the most comfortable road(

思路:把边排序,枚举起点,并查集判断 是否U,V连上(判断终点),终点-起点就是答案。

#include<bits/stdc++.h>
using namespace std;
struct Edg
{
	int u, v, w;
	bool operator < (const Edg &p) const
	{
		return w < p.w;
	}
}edg[2000];

int Father[2000];
int FindFather(int x)
{
	return Father[x] <0? x: FindFather(Father[x]);
}
void Umerge(int x,int y)
{
	int Fx = FindFather(x), Fy = FindFather(y);
	if (Fx != Fy)Father[Fx] = Fy;
}

int main()
{
	ios_base::sync_with_stdio(0);
	int n, m;
	while (cin>>n&&n)
	{
		cin >> m;
		for (int i = 0; i<m; i++)  cin>>edg[i].u>>edg[i].v>>edg[i].w;
		sort(edg, edg + m);
		int u, v, Q;
		cin >> Q;
		while (Q--)
		{
			cin >> u >> v;
			int ans = INT_MAX;
	
			for (int i = 0; i<m; i++)
			{
				memset(Father, -1, sizeof(Father));
				for (int j = i; j<m; j++)
				{
					Umerge(edg[j].u,edg[j].v);
					if (FindFather(u) == FindFather(v))
					{
						ans = min(ans, edg[j].w - edg[i].w);
						break;
					}
				}
			}
			ans == INT_MAX ?printf("-1\n"):printf("%d\n", ans);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_31741481/article/details/83310668