hdu1598 find the most comfortable road(并查集+贪心)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1598

题目思路:把所有的边从小到大排序,然后从最小的边开始枚举。

代码:

#include 
#include 
#include 
#include 
#include 
#include 


using namespace std;

const int maxn =200+5;
int fa[maxn];

void init()
{
    for(int i=0; iint find_(int x)
{
    if(fa[x]==x)
        return x;
    else
        return x=find_(fa[x]);
}

struct Edge
{
    int from,to,val;
    bool operator <(const Edge& rhs)const
    {
        return val 1000+5];


int main()
{
    int N,M,x,y,min_;
    int q,s,e1;

    while(scanf("%d%d",&N,&M)!=EOF)
    {
        for(int i=0; iscanf("%d %d %d",&e[i].from,&e[i].to,&e[i].val);
        }

        sort(e,e+M);
        scanf("%d",&q);
        while(q--)
        {
            min_=10000000;
            scanf("%d%d",&s,&e1);
            for(int i=0; ifor(int j=i; jif(x!=y)
                    {
                        fa[x]=y;
                    }
                    if(find_(s)==find_(e1))
                    {
                        min_=min(min_,e[j].val-e[i].val);
                        break;
                    }
                }
            }
            if(min_==10000000)
                printf("-1\n");
            else
                printf("%d\n",min_);

        }
    }
    return 0;
}

你可能感兴趣的:(hdu1598 find the most comfortable road(并查集+贪心))