Agri-Net poj 1258

WA了好多次,注意语言和数据范围

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

题目大意:一个人当村长,想共享光纤,输入的是图,求最小生成树;

思路: 按无向图处理;

1.图转化成点到点的距离并储存起来

2.按权有小到大排序

3.Kruskal算法+并查集 构建最小生成树

 #include<stdio.h>
#include<stdlib.h>
struct node
{
int i,j;
int weight;
} s[];
int cmp(const void*a,const void *b)
{
return (*(node*)a).weight-(*(node*)b).weight;
}
int v[];
int findl(int n)
{
return v[n]==n?n:findl(v[n]);
}
int main()
{
int n,i,j,k,a,sum;
while(~scanf("%d",&n))
{
n++,k=,sum=;
for(i=; i<; i++)
v[i]=i;
for(i=; i<n; i++)
{
for(j=; j<n; j++)
{
scanf("%d",&a);
if(j>i)//0及以下的数字直接忽略
{
s[k].weight=a;
s[k].i=i,s[k].j=j,k++;
}
}
}
qsort(s,k,sizeof(node),cmp);//按权值从小到大排序
for(i=; i<k; i++)
{
if(findl(s[i].i)!=findl(s[i].j))//简单的并查集
{
sum+=s[i].weight;
v[findl(s[i].i)]=s[i].j;
}
}
printf("%d\n",sum);
}
return ;
}
上一篇:使用JMeter创建数据库(Mysql)测试


下一篇:OSTaskCreateExt() 建立任务