试题编号: | 201703-4 |
试题名称: | 地铁修建 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 A市有n个交通枢纽,其中1号和n号非常重要,为了加强运输能力,A市决定在1号到n号枢纽间修建一条地铁。 输入格式 输入的第一行包含两个整数n, m,用一个空格分隔,分别表示交通枢纽的数量和候选隧道的数量。 输出格式 输出一个整数,修建整条地铁线路最少需要的天数。 样例输入 6 6 样例输出 6 样例说明 可以修建的线路有两种。 评测用例规模与约定 对于20%的评测用例,1 ≤ n ≤ 10,1 ≤ m ≤ 20; |
/*---并查集的使用---*/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXV=100001;//最大顶点数
const int MAXE=200001;
struct edge{//边的结构体
int u,v;
int cost;
}E[MAXE];
bool cmp(edge a,edge b){
return a.cost<b.cost;
}
int father[MAXV];//并查数组集
int findFather(int x){//并查集查询函数
int a=x;
while(x!=father[x]){
x=father[x];
}
//路径压缩
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
int main(){
int n,m;
int u,v,w;
cin>>n>>m;
for(int i=0;i<m;i++){//输入图
cin>>E[i].u>>E[i].v>>E[i].cost;
}
for(int i=1;i<=n;i++){//顶点范围从1--n
father[i]=i;//并查集初始化
}
sort(E,E+m,cmp);//将边按权值排序,一次挑最小的边并入集合,直到打通了1--n就停止
for(int i=0;i<m;i++){
int x=findFather(E[i].u);
int y=findFather(E[i].v);
father[x]=y;//合并集合
if(findFather(1)==findFather(n)){
cout<<E[i].cost;
return 0;
}
}
}
更多相关CCF的试题解答,请点击>>CCF历年认证考试解答