zoukankan      html  css  js  c++  java
  • P1111 修复公路(并查集)

    题目背景

    AA地区在地震过后,连接所有村庄的公路都造成了损坏而无法通车。政府派人修复这些公路。

    题目描述

    给出A地区的村庄数NN,和公路数MM,公路是双向的。并告诉你每条公路的连着哪两个村庄,并告诉你什么时候能修完这条公路。问最早什么时候任意两个村庄能够通车,即最早什么时候任意两条村庄都存在至少一条修复完成的道路(可以由多条公路连成一条道路)

    输入输出格式

    输入格式:

    第11行两个正整数N,MN,M

    下面MM行,每行33个正整数x, y, tx,y,t,告诉你这条公路连着x,yx,y两个村庄,在时间t时能修复完成这条公路。

    输出格式:

    如果全部公路修复完毕仍然存在两个村庄无法通车,则输出-1−1,否则输出最早什么时候任意两个村庄能够通车。

    输入输出样例

    输入样例#1: 复制

    4 4
    1 2 6
    1 3 4
    1 4 5
    4 2 3

    输出样例#1: 复制

    5

    说明

    N le 1000,M le 100000N≤1000,M≤100000

    x le N,y le N,t le 100000x≤N,y≤N,t≤100000

    题解:过于简单,应该都会…………

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    
    using namespace std;
    int pre[10005];
    int find(int x)
    {
        if(x==pre[x])
        return x;
        else
        {
            return pre[x]=find(pre[x]);
        }
    }
    
    struct node
    {
        int x,y,w;
    }p[100005];
    bool merge(int  x,int y)
    {
        int fx=find(x);
        int fy=find(y);
        if(fx!=fy)
        {
            pre[fx]=fy;
            return true;
        }
        else
        {
            return false;
        }
    }
    bool cmp(node x,node y)
    {
        return x.w<y.w;
    }
    int main()
    {
        int n,m;
        cin>>n>>m;
        for(int t=1;t<=n;t++)
        {
            pre[t]=t;
        }
        for(int t=0;t<m;t++)
        {
            scanf("%d%d%d",&p[t].x,&p[t].y,&p[t].w);
        }
        sort(p,p+m,cmp);
        int cnt=0;
        int max=0;
        for(int t=0;t<m;t++)
        {
            if(cnt==n-1)
            {
                break;
            }
            if(merge(p[t].x,p[t].y))
            {
                cnt++;
                if(max<p[t].w)
                {
                    max=p[t].w;
                }
            }
        }
        if(cnt==n-1)
        cout<<max<<endl;
        else
        {
            cout<<"-1"<<endl;
        }
        return 0;
    }
  • 相关阅读:
    shell:定时任务crontab
    shell:采集进程的cpu和内存利用率_随手记1
    临时记录
    python:numpy库和matplotlib库
    python:urllib:HTTPResponse对象的用法
    美国亚马逊图片打不开
    互联网协议
    range 和 xrange
    国内服务器的端口开放问题
    Mac上设置Chrome跨域
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10782075.html
Copyright © 2011-2022 走看看