POJ 1258-Agri-Net

POJ 1258-Agri-Net Agri-Net Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 40975 Accepted: 16713 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 Source USACO 102


这一题相对第2485来说就更是彻头彻尾的最小生成树了。它要求的是最小生成树的总长度,所以对2485稍微修改即可。需要注意的是题目中有这么一句话:
The input includes several cases.
也就是说有多个测试用例,而不是直接告诉你有几个用例或者结束标志是0 0 0之类的,我一开始写成了 [cpp] while(1) { scanf("%d",&n); … } [/cpp] 这样就变成了有无穷个测试用例了,根本停不下来,所以Time Limit Exceeded好几次,后来改成这样就好了: [cpp] while(scanf("%d",&n)!=EOF) { … } [/cpp] 完整的代码如下: [cpp] #include<stdio.h> int a[101][101]; int lowcost[101]; //int closet[101]; const static int MAX_DIS=100001; //最长距离 //prim算法求最小生成树 int prim(int n) { for(int i=0;i<n;i++) { lowcost[i]=a[0][i]; //closet[i]=0;//这个数组可以不要 } int total_min_len=0; int k,curr_min_len; for(int t=0;t<n-1;t++) { k=0; curr_min_len=MAX_DIS; for(int i=0;i<n;i++) { if(lowcost[i]!=0&&lowcost[i]<curr_min_len) { curr_min_len=lowcost[i]; k=i; } } total_min_len+=curr_min_len;//这题才是求和 //if(curr_min_len>total_min_len)//注意看题,求最小生成树中的最长路径 // total_min_len=curr_min_len; lowcost[k]=0; for(int i=0;i<n;i++) { if(a[i][k]!=0&&a[i][k]<lowcost[i]) { lowcost[i]=a[i][k]; //closet[i]=k; } } } return total_min_len; } int main() { int n; //while(1)//The input includes several cases.并不代表case无穷 while(scanf("%d",&n)!=EOF) { //scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<n;j++) scanf("%d",&a[i][j]); printf("%d\n",prim(n)); } return 0; } [/cpp] 本代码提交AC,用时16MS,内存172K。可以看到内存明显比2485题少了,那是因为我把closet数组删了,因为常规的最小生成树不需要这个变量。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *