您的位置:首页 > 其它

hud 1598_ find the most comfortable road_并查集

2017-07-03 11:28 411 查看

题目描述

XX星有许多城市,城市之间通过一种奇怪的高速公路SARS(Super Air Roam Structure—超级空中漫游结构)进行交流,每条SARS都对行驶在上面的Flycar限制了固定的Speed,同时XX星人对 Flycar的“舒适度”有特殊要求,即乘坐过程中最高速度与最低速度的差越小乘坐越舒服 ,(理解为SARS的限速要求,flycar必须瞬间提速/降速,痛苦呀 ),

但XX星人对时间却没那么多要求。要你找出一条城市间的最舒适的路径。(SARS是双向的)

思路

将边权从小到大排序,则有对于一条边来说,离这条边近的边和它的差值肯定比离它远的差值小

那么我们枚举边权,每次取一条边作为最小的边,然后用kruskal+并查集来每次取一条边,直到起点和终点在同一集合里,判断是否为最优解就可以了

#include <stdio.h>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
#define maxn 10001
#define fill(x, y) memset(x, y, sizeof(x))
struct edge
{
int x, y, w;
}e[maxn];
int f[maxn];
int find(int x)
{
if (f[x] == x) return x;
f[x] = find(f[x]);
return f[x];
}
int insert(int x, int y)
{
if (find(x) != find(y))
{
f[find(x)] = find(y);
return 0;
}
return 0;
}
int cmp
4000
(edge a, edge b)
{
return a.w < b.w;
}
int main()
{
int n, m;
while (~scanf("%d%d", &n, &m))
{
for (int i = 1; i <= m; i++)
scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].w);
sort(e+1, e+m+1, cmp);
int u;
scanf("%d", &u);
for (int i = 1; i <= u; i++)
{
int start, end;
int ans = 0x7fffffff;
scanf("%d%d", &start, &end);
for (int j = 1; j <= m; j++)
{
for (int k = 1; k <= n; k++)
f[k] = k;
for (int k = j; k <= m; k++)
{
insert(e[k].x, e[k].y);
if (find(start) == find(end))
{
if (e[k].w - e[j].w < ans)
ans = e[k].w - e[j].w;
break;
}
}
}
if (ans == 0x7fffffff) printf("-1\n");
else printf("%d\n", ans);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: