Agri-Net
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 52620 Accepted: 21936
Description
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
【分析】
最小生成树的Kruskal算法,用到并查集与贪心思想,这是裸题。
【代码】
//例2.Kruskal:最短网络
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
int n,m,k,tot; //k:计数器
int g[101][101],father[101];
struct chai
{
int x,y,v;
}a[10001];
int comp(const chai &c,const chai &d)
{
if(c.v<d.v) return 1;
return 0;
}
int find(int x)
{
if(x!=father[x]) father[x]=find(father[x]);
return father[x];
}
int main()
{
int i,j,k,t;
while(scanf("%d",&n)==1)
{
k=0;m=0;tot=0;
fo(i,1,n) father[i]=i;
fo(i,1,n)
fo(j,1,n)
{
scanf("%d",&t);
if(t)
{
m++;
a[m].x=i;
a[m].y=j;
a[m].v=t;
}
}
sort(a+1,a+m+1,comp);
fo(i,1,m)
{
int r1=find(a[i].x),r2=find(a[i].y);
if(r1!=r2)
{
father[r1]=r2;
tot+=a[i].v;
k++;
}
if(k==n-1) break;
}
printf("%d\n",tot);
}
return 0;
}