1576: 最小生成树
时间限制: 1 Sec 内存限制: 128 MB
提交: 340 解决: 145
[提交][状态][讨论版]
题目描述
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 <= 500). The following lines contain the N x N conectivity matrix, where each element shows the distance from one farm to another. Logically, they are N lines of N space-separated integers. 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.
样例输入
6 0 6 1 5 100 100 6 0 5 100 3 100 1 5 0 5 6 4 5 100 5 0 100 2 100 3 6 100 0 6 100 100 4 2 6 0
样例输出
15
#include<bits/stdc++.h>
using namespace std;
struct ss
{
int m;
int n;
int d;
}a[500*500+5];
bool cmp(ss x,ss y)
{
if(x.d!=y.d) return x.d<y.d;
else if(x.m!=y.m) return x.m<y.m;
else return x.n<y.n;
}
int x[500*500+5];
int F(int m)
{
if(x[m]==-1)
return m;
else return x[m]=F(x[m]);
}
int main()
{
int n;
while(scanf("%d",&n)==1)
{
int k=0,p,num=0;
memset(x,-1,sizeof(x));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&p);
a[k].m=i;
a[k].n=j;
a[k].d=p;
k++;
}
}
sort(a,a+k,cmp);
int ans=0;
for(int i=0;i<k&&num<n-1;i++)
{
int e,f;
e=F(a[i].m);
f=F(a[i].n);
if(e!=f)
{
x[e]=f;
ans+=a[i].d;
num++;
}
}
printf("%d\n",ans);
}
return 0;
}