最小生成树Kuskal算法应用
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
最小生成树Kuskal算法应用。
注意只需要关注不重复的点之间的边,输入的矩阵是对称的,只需用到上/下半矩阵的两点及边权。
包含了并查集的应用。
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<iostream>
//#include<random>
#include<functional>
#include<list>
#include<cstdlib>
#include<stdlib.h>
#include<vector>
#define lld long long int
#define INF 0x7fffffff
using namespace std;
//int dis[105][105];
struct edge
{
int u, v, cost;
}es[10005];
bool comp(edge a, edge b)
{
return a.cost < b.cost;
}
int parent[1000];
int height[1000];
int n;
void init()
{
for (int i = 0;i < n;i++)
{
parent[i] = i;
height[i] = 0;
}
}
int find(int x)
{
if (parent[x] == x)return x;
else return parent[x] = find(parent[x]);
}
void unite(int x, int y)
{
int a = find(x);
int b = find(y);
if (height[a] < height[b])
parent[a] = b;
else
{
parent[b] = a;
if (height[a] == height[b])
{
height[b]++;
}
}
}
bool same(int x, int y)
{
int a = find(x);
int b = find(y);
return a==b ? 1 : 0;
}
int main()
{
while (~scanf("%d",&n))
{
int cnt = 0;
for (int i = 0;i < n;i++)
for (int j = 0;j < n;j++)
{
int a;
scanf("%d", &a);
if (j > i)
{
es[cnt].u = i;
es[cnt].v = j;
es[cnt].cost = a;
cnt++;
}
}
init();
sort(es, es + cnt, comp);
int ans = 0;
for (int i = 0;i < cnt;i++)
{
edge e = es[i];
if (!same(e.u, e.v))
{
unite(e.u, e.v);
ans += e.cost;
}
}
printf("%d\n", ans);
}
return 0;
}