Time Limit: 1000ms
Memory Limit: 10000KB
64-bit integer IO format: %lld Java class name: Main
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
AC代码(110ms 740KB):
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int MAXN=105,INF=0x3f3f3f3f;
int edge[MAXN][MAXN],lowcost[10005],closest[10005],T;
int prime(int v0,int n)
{
lowcost[v0]=-1;
for(int i=1;i<=n;i++)
if(i!=v0)
lowcost[i]=edge[i][v0],closest[i]=v0;
int res=0;
for(int i=1;i<n;i++)
{
int minval=INF,k;
for(int j=1;j<=n;++j)
if(lowcost[j]!=-1&&lowcost[j]<minval)
{
minval=lowcost[j];
k=j;
}
res+=minval;
lowcost[k]=-1;
for(int j=1;j<=n;++j)
if(lowcost[j]!=-1&&edge[j][k]<lowcost[j])
lowcost[j]=edge[j][k],closest[j]=k;
}
return res;
}
int main()
{
while(cin>>T){
for(int i=1;i<=T;++i)
{
for(int j=1;j<=T;++j)
{
cin>>edge[i][j];
}
}
cout<<prime(1,T)<<endl;}
}
WA,RE原因探索:
在用最大值标记时,用0x3f3f3f3f最有保证,其他值(65535)过小可能被覆盖,可能会RE。
数组可以开到刚刚好,也就是100,10000这种。
主函数范围内int n,其他函数中也可以用int n,可能是恰好在这个题中两者是一个数?
变量名和库函数名相同也不是WA的主要原因(用map,min试验都可以)。
WA的主要原因是cin时用[j][i](与prim函数中最初lowcost初始化的顺序相反)并且最初用来标记的最大值过小(主要是这个,只有第一个条件可以AC,只有第二个则会RE)。
在不用while(cin>>T)循环输入时(只用cin>>T;)会WA(虽然我也不知道为什么,加了endl换行也不可以)。