链接:https://vjudge.net/problem/POJ-1258#author=fuxianda
题意:
有n个农场,已知这n个农场都互相相通,有一定的距离,现在每个农场需要装光纤,问怎么安装光纤能将所有农场都连通起来,并且要使光纤距离最小,输出安装光纤的总距离
任意两个村庄之间的距离小于 100,000.
思路:
最小生成树
代码:
#include <iostream>
#include <memory.h>
#include <string>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <map>
#include <queue>
#include <math.h>
#include <cstdio>
using namespace std;
typedef long long LL;
const int MAXM = 10000+10;
const int MAXN = 100+10;
struct Node
{
double _x,_y;
}node[MAXN];
struct Path
{
int _l,_r;
double _value;
bool operator < (const Path & that)const{
return this->_value < that._value;
}
}path[MAXM];
int Father[MAXN];
double a[MAXN];
int n, m, v;
int s, p;
int pos;//边数
int Get_F(int x)
{
return Father[x] = (Father[x] == x) ? x : Get_F(Father[x]);
}
void Init(int x)
{
for (int i = 1;i <= x;i++)
Father[i] = i;
}
double Get_Len(Node a,Node b)
{
return sqrt((a._x - b._x) * (a._x - b._x) + (a._y - b._y) * (a._y - b._y));
}
int main()
{
while (cin >> n)
{
Init(n);
pos = 0;
for (int i = 1;i <= n;i++)
{
for (int j = 1;j <= n;j++)
{
cin >> v;
path[++pos]._l = i;
path[pos]._r = j;
path[pos]._value = v;
}
}
sort(path + 1,path + 1 + pos);
LL res = 0;
for (int i = 1;i <= pos;i++)
{
int tl = Get_F(path[i]._l);
int tr = Get_F(path[i]._r);
if (tl != tr)
{
Father[tl] = tr;
res += path[i]._value;
}
}
cout << res << endl;
}
return 0;
}