2018-12-4 数据中心 AC
注重对题目的透彻理解 其实就是求最小生成树并返回最小生成树的最大边
掌握Kruskal算法
使用结构体存储各边(一条边、两个顶点)
结构体排序cmp+sort
在这里插struct Edge//使用cmp以及sort(edge,edge+m,cmp)对结构体数组排序
{
int a,b,v;
}edge[maxn];
bool cmp(Edge a,Edge b)
{
return a.v<b.v;
}
// struct Edge 或使用重载关系符<以及sort(edge,edge+m)对结构体数组排序
// {
// int a,b,v;
// bool operator<(const Edge&W) const
// {
// return v<W.v;
// }
// }edge[maxn];
//sort(edge,edge+m)
Kruskal,并查集
int find(int x)//father[x]表示父节点,find函数返回x的根节点
{
return father[x] == x?x:father[x]=find(father[x]);
}
int Kruskal()
{
int res=0;
for(int i=1;i<=n;i++)
father[i]=i;
sort(edge,edge+m,cmp);
for(int i=0;i<m;i++)
{
int a=edge[i].a,b=edge[i].b;
if(find(a)!=find(b))
{
res=max(res,edge[i].v);
father[find(a)]=find(b);//合并
}
}
return res;
}
主函数
int main()
{
ios::sync_with_stdio(false);
//是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑到了一起。也就是 C++标准streams(cin,cout,cerr…) 与相应的C标准程序库文件(stdin,stdout,stderr)同步,使用相同的 stream 缓冲区。
//默认是同步的,但由于同步会带来某些不必要的负担,因此该函数作用是使得用户可以自行取消同步。
//关闭以后不可使用scanf/printf
// cin.tie(0);取消 cin 和 cout 的绑定。默认的情况下cin绑定的是cout,每次执行 << 操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。
// cout.tie(0);
cin>>n>>m>>root;
for(int i=0;i<m;i++)
cin>>edge[i].a>>edge[i].b>>edge[i].v;
cout<<Kruskal()<<'\n';
return 0;
}