zoukankan      html  css  js  c++  java
  • HDU-1598-find the most comfortable road(暴力+并查集)多看看,

    题目链接

    http://acm.hdu.edu.cn/showproblem.php?pid=1598

    题目思路:对于这个题目,可以先按速度的大小成小到大排序,

    再成0 到 m ,把所有可以联通的道路全部暴搜一遍,一但联通,

    两者的min=两者的速度差,依次成0  到 找 m  找,如果找到更最小的就取代min

    最后的min一定是最小的,

    看代码

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    using namespace std;

    int father[222];
    const int M=999999999;
    int n,m;

    struct node
    {
    int x,y,d;
    } s[1111];

    bool cmp(const node &a,const node &b)
    {
    return a.d<b.d;
    }

    int Find(int x)
    {
    if(x==father[x]) return x;
    father[x]=Find(father[x]);
    return father[x];
    }

    void Union(int x,int y)
    {
    x=Find(x);
    y=Find(y);
    if(x!=y)
    {
    father[x]=y;
    }
    }

    int slove(int x,int y)
    {
    int min,max,i,j,k;
    min=M;
    for(i=0; i<m; i++)
    {
    for(j=1; j<=n; j++)
    father[j]=j;
    for(j=i; j<m; j++)
    {
    Union(s[j].x,s[j].y);
    if(Find(x)==Find(y))//一旦两者联通,两者速度即相减
    {
    max=s[j].d-s[i].d;// 两者速度即相减。
    if(max<min)
    {
    min=max;//取最小的差值。
    break;
    }
    }
    }
    }
    if(min==M) return -1;
    else return min;
    }

    int main(void)
    {
    int i,j,k,l;
    int x,y,q;
    while(scanf("%d%d",&n,&m)==2)
    {
    for(i=0; i<m; i++)
    scanf("%d%d%d",&s[i].x,&s[i].y,&s[i].d);
    sort(s,s+m,cmp);
    scanf("%d",&q);
    while(q--)
    {
    scanf("%d%d",&x,&y);
    printf("%d ",slove(x,y));
    }
    }
    return 0;
    }

  • 相关阅读:
    css的书写位置+元素分类
    选择器
    我的js运动库新
    js的相关距离
    关于小乌龟的使用
    linux 基础
    linux shell快捷操作【超级实用】
    算法面试常见问题【转】
    http://www.cnblogs.com/zhangchaoyang/archive/2012/08/28/2660929.html
    cocos2dx + vs安装使用
  • 原文地址:https://www.cnblogs.com/liudehao/p/3941410.html
Copyright © 2011-2022 走看看