MST:Bad Cowtractors(POJ 2377)-LMLPHP

                 坏的牛圈建筑

  题目大意:就是现在农夫又要牛修建牛栏了,但是农夫想不给钱,于是牛就想设计一个最大的花费的牛圈给他,牛圈的修理费用主要是用在连接牛圈上

  这一题很简单了,就是找最大生成树,把Kruskal算法改一下符号就好了,把边从大到小排列,然后最后再判断是否联通(只要找到他们的根节点是否相同就可以了!)

  

 #include <iostream>
#include <algorithm>
#include <functional>
#define MAX_N 1005
#define MAX 20005 using namespace std; typedef int Position;
typedef struct _edge
{
Position from;
Position to;
int cost;
}Edge_Set;
int fcomp(const void *a, const void *b)
{
return (*(Edge_Set *)b).cost - (*(Edge_Set *)a).cost;
} static Edge_Set edge[MAX];
static Position Set[MAX_N]; Position Find(Position);
void Union(Position, Position);
void Kruskal(const int, const int);
bool Is_Connected(const int); int main(void)
{
int Node_Sum, Path_Sum, cost;
Position tmp_from, tmp_to; while (~scanf("%d%d", &Node_Sum, &Path_Sum))
{
for (int i = ; i < Path_Sum; i++)//读入边
{
scanf("%d%d%d", &tmp_from, &tmp_to, &cost);
edge[i].from = tmp_from; edge[i].to = tmp_to; edge[i].cost = cost;
}
qsort(edge, Path_Sum, sizeof(Edge_Set), fcomp);
Kruskal(Node_Sum, Path_Sum);
}
return ;
} Position Find(Position x)
{
if (Set[x] < )
return x;
else return Set[x] = Find(Set[x]);
} void Union(Position px, Position py)
{
if (Set[px] < Set[py])
{
Set[px] += Set[py];
Set[py] = px;
}
else
{
Set[py] += Set[px];
Set[px] = py;
}
} bool Is_Connected(const int Node_Sum)
{
Position p_u, p_tmp;
p_u = Find();
for (int i = ; i <= Node_Sum; i++)
{
p_tmp = Find(i);
if (p_u != p_tmp)
return false;
}
return true;
} void Kruskal(const int Node_Sum, const int Path_Sum)
{
Position px, py, from, to;
long long ans = ; fill(Set, Set + Node_Sum + , -);
for (int i = ; i < Path_Sum; i++)
{
from = edge[i].from; to = edge[i].to;
px = Find(from); py = Find(to); if (px != py)
{
ans += edge[i].cost;
Union(px, py);
}
}
if (Is_Connected(Node_Sum))
printf("%lld\n", ans);
else
printf("-1\n");
}

MST:Bad Cowtractors(POJ 2377)-LMLPHP

04-26 11:08