poj 1861 并查集+kruskal 解题报告

Network

Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 16921 Accepted: 6725 Special Judge
Description

Andrew is working as system administrator and is planning to establish a new network in his company. There will be N hubs in the company, they can be connected to each other using cables. Since each worker of the company must have access to the whole network, each hub must be accessible by cables from any other hub (with possibly some intermediate hubs).
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the maximum length of a single cable is minimal. There is another problem — not each hub can be connected to any other one because of compatibility problems and building geometry limitations. Of course, Andrew will provide you all necessary information about possible hub connections.
You are to help Andrew to find the way to connect hubs so that all above conditions are satisfied.

思路:

结构体:

记录节点x,y和权值d。写一个比较函数+sort使结构体按权值由小到大排序。

并查集:

两个集合被选中的和没被选中的。

kruskal:

初始化每个节点独自一个集合,每次输入不在一个集合的就合并并记录,在一个集合的不管。输出记录数组最后一个节点的权值(edge[c-1].d),记录数组大小(c-1),每条边(从1到c-1)【kruskal函数最后一次多了一个c++,脚标又是从1开始。

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=15000+5;
struct bian
{
    int x,y,d;
}edge[N],ans[N];
int fa[N],c=1,n,m;
int cmp(bian a, bian b)
{
    return a.d<b.d;
}
void init(int n)
{
    for (int i=1;i<=n;i++)
    fa[i]=i;
}
int found(int x)
{
    if(fa[x]==x) return x;
    else fa[x]=found(fa[x]);
    return fa[x];
}
void unite(int x,int y)
{
    int px=found(x);
    int py=found(y);
    if (px==py) return ;
    fa[py]=px;
}
void kruskal()
{
    for (int i=1;i<=m;i++)
    {
        int x=edge[i].x;
        int y=edge[i].y;
        if (found(x)!=found(y))//两顶点不在一个集合则把该边放入
        {
            unite(x,y);
            ans[c].x=x;
            ans[c].y=y;
            ans[c].d=edge[i].d;
            c++;
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);//n个点,m条边
    init(n);
    for(int i=1;i<=m;i++)
    scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].d);
    sort(edge+1,edge+m+1,cmp);//sort函数是从0到n-1的
    kruskal();
    printf("%d\n",ans[c-1].d);
    printf("%d\n",c-1);
    for(int i=1;i<c;i++)
    printf("%d %d\n",ans[i].x,ans[i].y);
    return 0;
}

数据结构还是很重要的。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值