大意:有一个小镇,镇上有一些农场。用以光纤把所有农场联通,最少需要多少光纤。
最小生成树,prim或者kruskal。
prim
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 100 + 5;
const int inf = 1e9 + 10;
int cost[maxn][maxn], mincost[maxn], n;
bool used[maxn];
void prim()
{
memset(used, 0, sizeof(used));
for(int i = 1; i <= n; i++)
mincost[i] = inf;
mincost[1] = 0;
int ret = 0;
while(true)
{
int v = -1;
for(int i = 1; i <= n; i++)
{
if(!used[i] && (v == -1 || mincost[i] < mincost[v]))
{
v = i;
}
}
if(v == -1) break;
ret += mincost[v];
//printf("%d\n", mincost[v]);
used[v] = 1;
for(int i = 1; i <= n; i++)
{
mincost[i] = min(mincost[i], cost[i][v]);
}
}
printf("%d\n", ret);
}
int main()
{
while(scanf("%d", &n) == 1)
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
int t1;
scanf("%d", &t1);
cost[i + 1][j + 1] = t1;
}
//printf("yes\n");
prim();
}
return 0;
}