题目链接:
http://poj.org/problem?id=2421
赤裸裸的最小生成树习题!
#include<iostream>
#include<string.h>
using namespace std;
const int INF=0x1f1f1f1f;//设置一个非常大的值,用于每次找出low数组最小值
int cost[101][101];
//记录每条双向边的权值
int low[101];
int f1[101],res;//标记是否加入最小生成树“”记录最小权值总和。
int prim(int n)
{
f1[1]=1;
for(int i=1; i<=n; i++)
{
low[i]=cost[1][i];
}
for(int i=1; i<n; i++)
{
int Min=INF,loc;
for(int i=1; i<=n; i++)
{
if(!f1[i]&&low[i]<Min)
{
Min=low[i];
loc=i;
}
}
f1[loc]=1;
res+=Min;
for(int i=1; i<=n; i++)
{
if(!f1[i]&&low[i]>cost[loc][i])
low[i]=cost[loc][i];
}
}
return res;
}
int main()
{
int n;
while(cin>>n)
{
res=0;
memset(low,0,sizeof(low));
memset(f1,0,sizeof(f1));
memset(cost,0,sizeof(cost));
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cin>>cost[i][j];
}
}
int t;
cin>>t;
for(int i=1; i<=t; i++)
{
int a,b;
cin>>a>>b;
cost[a][b]=0;
cost[b][a]=0;
}
cout<<prim(n)<<endl;
}
}