【训练题】极品飞车 (并查集)

来源:互联网 发布:淘宝企业店铺搜索权重 编辑:程序博客网 时间:2024/06/07 11:49

【问题描述】

  FC星有许多城市,城市之间通过一种奇怪的双向高速公路进行交流,每条公路都对行驶在上面的飞车限制了固定的速度,同时FC星人对飞车的“舒适度”有特殊要求,即乘坐过程中最高速度与最低速度的差越小乘坐越舒服,但对时间却没那么多要求。要注意的是FC人的飞车能瞬间提速或降速。现在需要你找出一条城市间的最舒适的路径。

【输入格式】

  第一行有2个正整数N(1

#include<cstdio>#include<vector>#include<cstring>#include<iostream>#include<algorithm>#define maxn 100005using namespace std;int n,m,t,x,y,z,front,rear;int fa[maxn];bool vis[maxn];struct data{    int a,b,l;};vector<data>g;int find(int x){    if(fa[x]==x) return x;    int root=find(fa[x]);    fa[x]=root;    return root; }void clear()            {for(int i=0;i<=n;i++) fa[i]=i;}void Union(int x,int y) {fa[find(y)]=find(x);}bool check(int x,int y) {return find(x)==find(y);}bool cmp(data m,data n) {return m.l<n.l;}int task(){    int ta=1000000005;    for(int i=0;i<m;i++)    {        clear();        for(int j=i;j<m;j++)        {            int p=g[j].a,q=g[j].b;            Union(p,q);            if(check(x,y))            {                ta=min(ta,g[j].l-g[i].l);                break;            }        }    }    if(ta==1000000005) return -1;    return ta;}int main(){    //freopen("in.txt","r",stdin);    scanf("%d%d",&n,&m);    clear();    for(int i=0;i<m;i++)    {        scanf("%d%d%d",&x,&y,&z);        g.push_back((data){x,y,z-1});    }    sort(g.begin(),g.end(),cmp);    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&x,&y);        int ans=task();        printf("%d\n",ans);    }    return 0;}
0 0