POJ 1258 Agri-Net
来源:http://poj.org/problem?id=1258
归类: 图论、最小生成树、Prim
Agri-Net
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 40209 | Accepted: 16380 |
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
#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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。