您的位置:首页 > 其它

Kruskal HDOJ 1233 还是畅通工程

2015-05-18 20:23 363 查看
题目传送门

 /*
最小生成树之kruskal算法--并查集(数据结构)实现
建立一个结构体,记录两点和它们的距离,依照距离升序排序
不连通就累加距离,即为最小生成树的长度
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

const int MAXN = 5e3 + 10;
const int INF = 0x3f3f3f3f;
int rt[MAXN];
struct Node
{
int u, v, w;
}node[MAXN];

bool cmp(Node x, Node y) {return x.w < y.w;}

int Find(int x)    {return (rt[x] == -1) ? x : rt[x] = Find (rt[x]);}

void Union(int x, int y)
{
x = Find (x);    y = Find (y);
if (x > y)    rt[y] = x;
else if (x < y)    rt[x] = y;
}

bool same(int x, int y)    {return (Find (x) == Find (y));}

int main(void)        //HDOJ 1233 还是畅通工程
{
//freopen ("inB.txt", "r", stdin);
int n, m;

while (~scanf ("%d", &n) && n)
{
m = n * (n - 1) / 2;
memset (rt, -1, sizeof (rt));
for (int i=1; i<=m; ++i)
{
scanf ("%d%d%d", &node[i].u, &node[i].v, &node[i].w);
}
sort (node+1, node+1+m, cmp);
int sum = 0;
for (int i=1; i<=m; ++i)
{
int x = node[i].u;    int y = node[i].v;
int w = node[i].w;
if (!same (x, y))    {Union (x, y);    sum += w;}
}
printf ("%d\n", sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: