来源:http://poj.org/problem?id=1258
归类: 图论、最小生成树、Prim
Agri-Net
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 40209 | Accepted: 16380 |
Description
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
#include<cstdio>
const int INF=1000000000;
int n,map[105][105],wage;
bool pa[105],pb[105];int pos;
void Prim(){
while(pos--){
int min=INF,x=0,y=0;
for(int i=1;i<=n;i++)
if(pa[i])
for(int j=1;j<=n;j++)
if(pb[j]&&map[i][j]&&min>map[i][j]){
min=map[i][j];x=i;y=j;
}
pb[y]=false;pa[y]=true;
wage+=min;
map[x][y]=0;map[y][x]=0;
}
}
int main(){
while(~scanf("%d",&n)){
wage=0;
for(int i=1;i<=n;i++) {
pa[i]=false; pb[i]=true;
} pa[1]=true;pb[1]=false; pos=n-1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&map[i][j]);
Prim();
printf("%d\n",wage);
}
return 0;
} #include <iostream>
#include <cstring>
using namespace std;
const int V=110;
const int MAXINT=0x3f3f3f3f;
int map[V][V],dist[V],vist[V];
int n,i,j,m,minn,ans;
int main()
{
while (cin>>n){
ans=0;
memset(vist,0,sizeof(vist));
for (i=1;i<=n;++i)
for (j=1;j<=n;++j)
cin>>map[i][j];
for (i=1;i<=n;++i)
dist[i]=map[1][i];
vist[1]=1;
for (i=1;i<n;++i){
minn=MAXINT;
for (j=1;j<=n;++j)
if (!vist[j] && dist[j]<minn){
minn=dist[j]; m=j;
}
ans+=minn;
for (j=1;j<=n;++j)
dist[j]=dist[j]>map[m][j]?map[m][j]:dist[j];
vist[m]=1;
}
cout<<ans<<endl;
}
return 0;
}POJ 1258 Agri-Net,布布扣,bubuko.com
原文地址:http://blog.csdn.net/mummyding/article/details/38656733