poj 2377最大生成树 Kruskal
2016-07-12 21:34
253 查看
点击打开链接
#include <iostream>
#include <algorithm>
using namespace std;
const int M = 21010;
struct edge{
int u;
int v;
long long cost;
bool operator <(const edge &t)const
{
return cost>t.cost;
}
}e[M];
int n,m,fa[M];
void Inin()
{
for(int i=1;i<=n;i++)
{
fa[i]=i;
}
}
int find(int x)
{
if(x!=fa[x])
{
fa[x]=find(fa[x]); //路径压缩
}
return fa[x];
}
void Union(int x,int y)
{
int a=find(x);
int b=find(y);
if(a!=b)
{
fa[a]=b;
}
}
void Kruskal()
{
Inin();// union-set 初始化
long long ans=0;
for(int i=0;i<m;i++)
{
if(find(e[i].u)!=find(e[i].v))
{
Union(e[i].u,e[i].v);
ans+=e[i].cost;
n--;
}
if(n==1)
break;
}
if(n==1)
cout<<ans<<endl;
else// 连不通
cout<<-1<<endl;
}
int main()
{
cin>>n>>m;
for(int i=0;i<m;i++)
{
cin>>e[i].u>>e[i].v>>e[i].cost;
}
sort(e,e+m);
Kruskal();//将n个连通分量变减少至1个(最小生成树)时 所用花费最少
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
const int M = 21010;
struct edge{
int u;
int v;
long long cost;
bool operator <(const edge &t)const
{
return cost>t.cost;
}
}e[M];
int n,m,fa[M];
void Inin()
{
for(int i=1;i<=n;i++)
{
fa[i]=i;
}
}
int find(int x)
{
if(x!=fa[x])
{
fa[x]=find(fa[x]); //路径压缩
}
return fa[x];
}
void Union(int x,int y)
{
int a=find(x);
int b=find(y);
if(a!=b)
{
fa[a]=b;
}
}
void Kruskal()
{
Inin();// union-set 初始化
long long ans=0;
for(int i=0;i<m;i++)
{
if(find(e[i].u)!=find(e[i].v))
{
Union(e[i].u,e[i].v);
ans+=e[i].cost;
n--;
}
if(n==1)
break;
}
if(n==1)
cout<<ans<<endl;
else// 连不通
cout<<-1<<endl;
}
int main()
{
cin>>n>>m;
for(int i=0;i<m;i++)
{
cin>>e[i].u>>e[i].v>>e[i].cost;
}
sort(e,e+m);
Kruskal();//将n个连通分量变减少至1个(最小生成树)时 所用花费最少
return 0;
}
相关文章推荐
- include标签布局和自定义标题
- C#属性
- MapReduce之Mapper中的方法分析
- centos linux 安装配置apc 内存缓存
- 平凡的生活(三)——等不了的昨天
- 阿里云反欺诈——风险识别
- 序列化一组对象
- [置顶] php+中文分词scws+sphinx+mysql打造千万级数据全文搜索
- CentOS 64位编译Hadoop2.6源码
- js解析XML
- andoird Xml解析XmlPullParser 的使用
- 另一种实现非阻塞网络通信的方法———使用libev
- 使用activity中遇到的问题及解决办法
- Python 小甲鱼教程 课后练习25 关于字典
- 在一个分时操作系统中,进程出现由运行状态进入就绪状态,由阻塞状态进入就绪状态的原因分别可能是()
- Linux CPUidle
- c语言实现快速排序
- SparseArray浅析
- hibernate_validator_01
- Remainders Game