这个题目是让你求出联通所有点所需要的最小代价,就是最小生成树问题.之前学过Kruskal算法,就用并查集写了个最小生成树的生成算法.
Kruskal算法:将边按权重大小排序,每次取权重最小的边,如果两个点属于不同的集合,归并,否则遍历下一条边,直到所有点都在同一集合,归并结束.
总时间限制: 1000ms 内存限制: 65536kB
**描述**
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.
**输入**
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.
**输出**
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.
**样例输入**
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
**样例输出**
28
来源
USACO 102
/*
内存: 1920kB
时间: 8ms
语言: G++
*/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char c;
long long res;
int n, num, val, tot;
int father[300];
struct edge
{
int left, right, is_used, val;
edge(){
is_used = 0, left = 0, right = 0;
}
}e[100000];
int root(int x)
{
if(x == father[x])
return father[x];
father[x] = root(father[x]);
return father[x];
}
void Union(int x,int y)
{
int fx = root(x);
int fy = root(y);
if(fx != fy)
father[fx] = fy;
}
bool cmp(edge a,edge b)
{
return a.val<b.val;
}
int main()
{
while(cin>>n)
{
res = 0;
memset(e,0,sizeof(e));
for(int i=1;i<=n;i++)
father[i] = i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&val);
if(i < j)
{
e[tot].left = i, e[tot].right = j, e[tot++].val = val;
}
}
sort(e,e+tot,cmp);
for(int i=0;i<tot;i++)
{
if(root(e[i].left) != root(e[i].right))
{
Union(e[i].left,e[i].right);
e[i].is_used = 1;
}
}
for(int i=0;i<tot;i++)
if(e[i].is_used)
res += e[i].val;
printf("%d\n",res);
}
return 0;
}