如题:http://poj.org/problem?id=1258
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 42375 | Accepted: 17317 |
Description
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
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
Source
题目大意:给出N*N的邻接矩阵,求最小生成树。
完全模板题,熟悉一下prim
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define min(a,b)(a<b?a:b)
int N;
int edge[105][105];
int prim()
{
int mincost[105]={0};
int vis[105]={0};
int i,j,res=0;
vis[1]=1;
for(i=1;i<=N;i++)
mincost[i]=edge[1][i];
for(i=0;i<N-1;i++)
{
int v=-1;
for(j=1;j<=N;j++)
if(!vis[j]&&(v==-1||mincost[v]>mincost[j]))
v=j;
vis[v]=1;
res+=mincost[v];
for(j=1;j<=N;j++)
mincost[j]=min(mincost[j],edge[v][j]);
}
return res;
}
int main()
{
// freopen("C:\\1.txt","r",stdin);
while(~scanf("%d",&N))
{
memset(edge,0,sizeof(edge));
int i,j;
for(i=1;i<=N;i++)
for(j=1;j<=N;j++)
scanf("%d",&edge[i][j]);
int res=prim();
cout<<res<<endl;
}
}