您的位置:首页 > 其它

POJ 1258 Agri-Net 图论 prim算法 最小生成树

2013-09-05 15:28 417 查看
Agri-Net
Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 33892Accepted: 13621
DescriptionFarmer 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.InputThe 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 thisproblem.OutputFor 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
个人感觉这个题和POJ2485很像,翻出POJ2485的程序稍微改了几行就AC了,就还是一个村长建网路,结果求连接所有村庄的总路径最短,其实还是最小生成树,画出图,然后代入prim模板,在模板中求出连接所有节点的最小总路径大小,并返回,输出这个数,其实题目就已经AC了,很简单的,而且还这么像。。。
下面是AC代码:
#include<cstdio>#include<iostream>using namespace std;#define infinity 100000#define max_vertexes 105int G[max_vertexes][max_vertexes];int prim(int vcount){int i,j,k,sum=0;int lowcost[max_vertexes],closeset[max_vertexes],used[max_vertexes];for (i=0;i<vcount;i++){lowcost[i]=G[0][i];closeset[i]=0;used[i]=0;}used[0]=1;for (i=1;i<vcount;i++){j=0;while (used[j]) j++;for (k=0;k<vcount;k++)if ((!used[k])&&(lowcost[k]<lowcost[j])) j=k;sum+=G[j][closeset[j]];used[j]=1;for (k=0;k<vcount;k++)if (!used[k]&&(G[j][k]<lowcost[k])){ lowcost[k]=G[j][k];closeset[k]=j; }}return sum;}int main(){int i,j,n;while(scanf("%d",&n)!=EOF){for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&G[i][j]);printf("%d\n",prim(n));}return 0;}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: