#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
#define MAXN 200 + 1
#define MAXM 1000 + 1
#define inf (~0u >> 1)
int n, m;
struct Edge
{
int u, v, w;
}edge[MAXM];
int pre[MAXN];
bool vis[MAXN];
bool cmp(Edge a, Edge b)
{
return a.w < b.w;
}
int find(int x)
{
int father, t, son = x;
while (x != pre[x])
{
x = pre[x];
}
father = x;
while (son != father)
{
t = pre[son];
pre[son] = father;
son = t;
}
return x;
}
void input()
{
int u, v, w;
while (cin >> n >> m)
{
for (int i = 0; i < m; i++)
{
cin >> u >> v >> w;
edge[i].u = u;
edge[i].v = v;
edge[i].w = w;
}
sort(edge, edge + m, cmp);
int k;
cin >> k;
while (k--)
{
int s, e, ans = inf;
cin >> s >> e;
for (int i = 0; i < m; i++)
{
int j = 0;
for (j = 0; j <= n; j++)
{
pre[j] = j;
}
memset(vis, false, sizeof(vis));
int num = 0;
for (j = i; j < m; j++)
{
int fu = find(edge[j].u), fv = find(edge[j].v);
if (fu != fv)
{
vis[fu] = vis[fv] = true;
pre[fu] = fv;
if (find(s) == find(e))
{
ans = min(ans, edge[j].w - edge[i].w);
break;
}
}
}
}
if (ans == inf)
{
cout << -1 << endl;
}
else
{
cout << ans << endl;
}
}
}
}
int main()
{
input();
return 0;
}
hdu 1598 枚举+并差集
最新推荐文章于 2021-10-11 16:16:31 发布