修复公路
题目背景
A地区在地震过后,连接所有村庄的公路都造成了损坏而无法通车。政府派人修复这些公路。
题目描述
给出A地区的村庄数N,和公路数M,公路是双向的。并告诉你每条公路的连着哪两个村庄,并告诉你什么时候能修完这条公路。问最早什么时候任意两个村庄能够通车,即最早什么时候任意两条村庄都存在至少一条修复完成的道路(可以由多条公路连成一条道路)
输入格式
第1行两个正整数N,M
下面M行,每行3个正整数x, y, t告诉你这条公路连着x,y两个村庄,在时间t时能修复完成这条公路。
输出格式
如果全部公路修复完毕仍然存在两个村庄无法通车,则输出-1,否则输出最早什么时候任意两个村庄能够通车。
输入案例
4 4
1 2 6
1 3 4
1 4 5
4 2 3
输出案例
5
题目大意
题目意思就是给你道路联通的时间和村庄,让你判断什么时候所有村庄能全部连通既从一个村庄能走到任意一个村庄
算法分析
使用并查集和kruskal算法(生成最小树);最小生成树大概的意思就是有多个通路的时候,能找到时间花费最短的一条通路.所有这道题就是找到道路的源头,然后遍历这个源头的路径,只要全部能走通就说明所有的村庄联通;
代码实现
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<map>
#include<set>
#include<string>
#include<stack>
#include<queue>
#include<vector>
#include<math.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long int ll;
const int maxn=1e6+5;
int t,n,m;
int rt[maxn];//源头
struct node
{
int t,w,sj;
}edge[maxn];//道路定义
bool cmp(const node &a,const node &b)//(最小生成树的关键,排序始终选择当前可用的最小边权的边)
{
return a.sj<b.sj;
}
void inti(int n)//初始化每个源头开始是本身
{
for(int i=0;i<n;i++)
{
rt[i]=i;
}
}
int fdroot(int x)//找源头函数
{
if(rt[x]==x)
return x;
else
return rt[x]=fdroot(rt[x]);
}
void join(int x,int y)//合并源头
{
int rx=fdroot(x);
int ry=fdroot(y);
if(rx!=ry)
{
rt[rx]=ry;
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<m;i++)//输入数据
{
int x,y,t;
cin>>x>>y>>t;
edge[i].t=x,edge[i].w=y,edge[i].sj=t;
}
inti(n);
sort(edge,edge+m,cmp);//(最小生成树的关键,排序始终选择当前可用的最小边权的边)
int k=0;int sum=0;
for(int i=0;i<m;i++)
{
if(k==n-1) break;//n个点只需要n-1条边就能联通
if(fdroot(edge[i].t)!=fdroot(edge[i].w))//如果源头不是本身
{
join(edge[i].t,edge[i].w);
sum=max(sum,edge[i].sj);
k++;
}
}
if(k!=n-1)
{
cout<<-1<<endl;
}
else
cout<<sum<<endl;
return 0;
}