MST:Agri-Net(POJ 1258)

时间:2022-11-05 11:28:24

            MST:Agri-Net(POJ 1258)

              Agri-Net

  题目大意:农夫有一片农场,现在他要把这些田地用管子连起来,田地之间有一定距离,铺设每一段管子的长度与这些田地与田地距离是一样的,问你最小的铺设方案。

  这一题很裸,Kruskal算法即可,不过一定要注意,这一题是多组数据输入,边的总数记得初始化!

  

 #include <iostream>
#include <functional>
#include <algorithm>
#define MAX 12100
#define MAX_N 110 using namespace std; typedef int Position;
typedef struct _edge
{
int cost;
Position to;
Position from;
}Edge_Set;
int fcomp(const void *a, const void *b)
{
return (*(Edge_Set *)a).cost - (*(Edge_Set *)b).cost;
} static Edge_Set edge[MAX * ];
static Position Set[MAX_N]; void Kruskal(const int, const int);
Position Find(Position);
bool If_Same(Position, Position);
void Union(Position, Position); int main(void)
{
int N, e_sum, tmp;
while (~scanf("%d", &N))
{
e_sum = ;
for (int i = ; i < N; i++)
{
for (int j = ; j < N; j++)
{
scanf("%d", &tmp);
if (i == j) continue;
edge[e_sum].from = i, edge[e_sum].to = j; edge[e_sum++].cost = tmp;
}
}
Kruskal(e_sum, N);
}
return ;
} Position Find(Position x)
{
if (Set[x] < )
return x;
else return Set[x] = Find(Set[x]);
} bool If_Same(Position x, Position y)
{
Position px, py;
px = Find(x); py = Find(y);
return px == py;
} void Union(Position x, Position y)
{
Position px, py;
px = Find(x); py = Find(y); if (px != py)
{
if (Set[px] < Set[py])
{
Set[px] += Set[py];
Set[py] = px;
}
else
{
Set[py] += Set[px];
Set[px] = py;
}
}
} void Kruskal(const int R_sum, const int Node_sum)
{
fill(Set, Set + Node_sum, -);
qsort(edge, R_sum, sizeof(Edge_Set), fcomp); Edge_Set e;
long long ans = ; for (int i = ; i < R_sum; i++)
{
e = edge[i];
if (!If_Same(e.from, e.to))
{
Union(e.from, e.to);
ans += e.cost;
}
}
printf("%lld\n", ans);
}

MST:Agri-Net(POJ 1258)