您的位置:首页 > 其它

poj 1258 小白算法练习 Agri-Net 最小生成树 prim kruskal

2017-08-10 11:40 633 查看
Agri-Net
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 60751 Accepted: 25170
DescriptionFarmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course. 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. InputThe input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N linesof N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.OutputFor each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
代码
【1】prim
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxiaml=101;
int map[maxiaml][maxiaml];//记录图的信息
int dist[maxiaml];//记录最短的边长
int pre[maxiaml];//前驱节点节点是否已经去除
int p[maxiaml];//表示
int prim(int n){ //n代表点的个数
int sum=0;
//初始化
for(int i=0;i<n;i++)
{
if(i==0)
{
pre[i]=-1;
dist[i]=0;
p[i]=true;
}
else
{
pre[i]=0;
dist[i]=map[0][i];
p[i]=false;
}
}
for(int i=0;i<n-1;i++)
{
//找到最短边
int min=INT_MAX;
int k=-1; //k用来记录点
for(int j=0;j<n;j++)
{
if(p[j]==false && dist[j]<min)
{
min=dist[j];
k=j;
}
}
sum+=dist[k];
if(k==-1) return sum;//已经没有点了
p[k]=true;
//更新
for(int j=0;j<n;j++){
if(p[j]==false && map[k][j]!=INT_MAX && dist[j]>map[k][j])
{
dist[j]=map[k][j];
pre[j]=k;
}
}
}
return sum;
}
int main(){

//	freopen("E://1001.txt","r",stdin);

int cases;
while(cin>>cases && cases!=EOF)
{
for(int i=0;i<cases;i++)
{
for(int j=0;j<cases;j++)
{
cin>>map[i][j];
}
}
cout<<prim(cases)<<endl;
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: