码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1233 还是畅通工程

时间:2016-05-06 12:33:57      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

Description

最小生成树

Algorithm

Kruskal算法
用C++实现了 UnionFind类
不过用JAVA写这题就一直WA,不知如何是好

Code

C++

#include <cstdio>
#include <algorithm>
using namespace std;
struct Edge
{
  int u, v, cost;
};
const int MAX_M = 109 * 108 / 2;
const int MAX_N = 100 + 9;
int n;
bool comp(Edge a, Edge b)
{
  if (a.cost < b.cost) return true; else return false;
}
struct UnionFind
{
  int n;
  int par[MAX_N];
  int rank[MAX_N];
  UnionFind(int nn)
  {
    n = nn;
    for (int i = 0; i < n; i++) {
      par[i] = i;
      rank[i] = i;
    }
  }
  int find(int x)
  {
    if (par[x] == x) return x;
    else return par[x] = find(par[x]);
  }
  void unite(int x, int y)
  {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (rank[x] < rank[y]) {
      par[x] = y;
    } else {
      par[y] = x;
      if (rank[x] == rank[y]) rank[x]++;
    }
  }
  bool same(int x, int y) {
    return find(x) == find(y);
  }
  void print()
  {
    for (int i = 0; i < n; i++) {
      printf("%d ", par[i]);
    }
  }
  int total()
  {
    int s = 0;
    for (int i = 0; i < n; i++) {
      if (par[i] == i) s++;
    }
    return s;
  }
};
void solve()
{
  int m = n * (n - 1) / 2;
  Edge edges[MAX_M];
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].cost);
  }
  sort(edges, edges + m, comp);
  UnionFind unionFind(n);
  int ans = 0;
  for (int i = 0; i < m; i++) {
    if (!unionFind.same(edges[i].u - 1, edges[i].v - 1)) {
      unionFind.unite(edges[i].u - 1, edges[i].v - 1);
      ans += edges[i].cost;
    }
  }
  printf("%d\n", ans);
}
int main()
{
  for (;;) {
    scanf("%d", &n);
    if (n == 0) break;
    solve();
  }
}

HDU 1233 还是畅通工程

标签:

原文地址:http://blog.csdn.net/yyecust/article/details/51328789

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!